-2

I have an array below.

var array = [
  { category: 'Input', field: 0, value: '17' },
  { category: 'Input', field: 0, value: '5' },
  { category: 'Input', field: 0, value: '8' },
  { category: 'Input', field: 5, value: '1' },
  { category: 'Input', field: 5, value: '4' },
  { category: 'Input', field: 0, value: '1' }
];

I want to convert the array-like below -- merge the objects based on the field value, if the value is same and get the result like below

[
  { category: 'Input', field: 0, value: ['17', '5', '8', '1'] },
  { category: 'Input', field: 5, value: ['1', '4'] }
];
michael
  • 4,053
  • 2
  • 12
  • 31
sravani
  • 13
  • 3

1 Answers1

-1

var array = [
  { category: 'Input', field: 0, value: '17' },
  { category: 'Input', field: 0, value: '5' },
  { category: 'Input', field: 0, value: '8' },
  { category: 'Input', field: 5, value: '1' },
  { category: 'Input', field: 5, value: '4' },
  { category: 'Input', field: 0, value: '1' }
];

const obj = array.reduce((val, cur) => {
  if (val[cur.field]) {
    val[cur.field].push(cur.value);
  } else {
    val[cur.field] = [cur.value];
  }
  return val;
}, {});

const res = Object.keys(obj).map(key => ({
  category: 'Input',
  field: parseInt(key),
  value: obj[key]
}));

console.log(res);
michael
  • 4,053
  • 2
  • 12
  • 31
  • Thank you so much @baymax , what should i do if category also differs like below ? var array = [ { category: 'Input', field: 0, value: '17' }, { category: 'Input', field: 0, value: '5' }, { category: 'Input', field: 0, value: '8' }, { category: 'Input', field: 5, value: '1' }, { category: 'Input', field: 5, value: '4' }, { category: 'Input', field: 0, value: '1' }, { category: 'output', field: 0, value: '1' }, ]; – sravani Dec 19 '20 at 06:37