Home > Back-end >  Manipulate objects in an array to include an array of other values in found in sibling objects
Manipulate objects in an array to include an array of other values in found in sibling objects

Time:03-16

I have an array that looks like this (simplified):

[
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5'],
    somethingElse: 6
  },
  {
    name: 'Store2',
    price: ['15'],
    somethingElse: 6
  },
]

I need to turn it into this:

[
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5', '15'],
    somethingElse: 6
  },
]

So for each object where the name is the same, it takes the price's for all of them and puts them in an array, and reduces amount of entries with the same name to one.

It needs to work for a much longer array, and work with many name's.

Let's assume that everything other than the price will be the same in each object that has the same name.

I have tried for too long using array.reduce but with no luck.

CodePudding user response:

const input = [
  {
    name: 'Store1',
    price: ['10'],
    somethingElse: null
  },
  {
    name: 'Store2',
    price: ['5'],
    somethingElse: 6
  },
  {
    name: 'Store2',
    price: ['15'],
    somethingElse: 6
  },
]

const output = input.reduce((a,c) => {
if(a.find(i => i.name === c.name)) { // Check if 'name' already exist 
    return a.map(el => el.name === c.name ? ({...el, price: [...el.price, ...c.price]}) : el) // updating price for existed name
} else {
    return [...a, c] // no such name, should add to ouput result
}
}, [])

console.log(output)

CodePudding user response:

You can use grouping by hash approach:

const data = [{"name":"Store1","price":["10"],"somethingElse":null},{"name":"Store2","price":["5"],"somethingElse":6},{"name":"Store2","price":["15"],"somethingElse":6}];

const result = Object.values(data.reduce((acc, obj) => {
  acc[obj.name] ??= obj;
  if (!acc[obj.name].price.includes(...obj.price)) 
    acc[obj.name].price.push(...obj.price);

  return acc;
}, {}));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related