Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
Group Object based on ending Number

Here is the sample object

{
  abc_0: 'a',
  bcd_0: 'b',
  cde_0: 'c',
  abc_1: 'a',
  bcd_1: 'b',
  cde_1: 'c',
  def_1: 'd',

}

I want to group via the number they end with and wante the expected output to be

{
 0: {abc: 'a', bcd: 'b', cde: 'c'},
 1: {abc: 'a', bcd: 'b', cde: 'c', def : 'd'},
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You may try this solution:

const data = {
  abc_0: 'a',
  bcd_0: 'b',
  cde_0: 'c',
  abc_1: 'a',
  bcd_1: 'b',
  cde_1: 'c',
  def_1: 'd',
};

const result = Object.entries(data).reduce((acc, [combo, value]) => {
  const [key, index] = combo.split('_');
  acc[index] = { ...acc[index], [key]: value };
  return acc;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You can write something like this to achieve it

const obj = {
  abc_0: 'a',
  bcd_0: 'b',
  cde_0: 'c',
  abc_1: 'a',
  bcd_1: 'b',
  cde_1: 'c',
  def_1: 'd',

};

const groupByChar = () => {
  const res = {};
  for (let k in obj){
    const char = k.charAt(k.length-1);
    if (!res[char]){
      res[char] = {};
    }

    const key = k.substring(0, k.length - 2);

    res[char][key] = obj[k];
  }
  
  return res;
}

const res = groupByChar();


console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

I deliberately disrupted the data sequence to better meet your needs.

const data = {
  abc_0: 'a',
  abc_1: 'a',
  bcd_0: 'b',
  bcd_1: 'b',
  cde_0: 'c',
  cde_1: 'c',
  def_0: 'd',
  def_1: 'd',
};

const res = Object.keys(data)
  .map((key) => {
    const [char, num] = key.split('_');
    return {
      [num]: {
        [char]: data[key],
      },
    };
  })
  .reduce((acc, cur) => {
    const acc_keys = Object.keys(acc);
    const [cur_key] = Object.keys(cur);
    if (acc_keys.includes(cur_key)) {
      acc[cur_key] = { ...acc[cur_key], ...cur[cur_key] };
      return {
        ...acc,
      };
    } else {
      return { ...acc, ...cur };
    }
  }, {});

console.log(res);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!