Home > other >  Group Object based on ending Number
Group Object based on ending Number

Time:12-08

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'},
}

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Something like this

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related