BitByte
BitByte

Reputation: 131

Combining values of json objects into an array with unique object keys and its values

I have an array of JSON objects that might or might not have common object key such as

const array = [ 
    {
      star: { apples: [ [Object], [Object] ] },
      circle: { apples: [ [Object] ] }
    },
    {
      star: { oranges: [ [Object], [Object] ] },
      circle: { oranges: [ [Object] ] }
    },
    { star: { bananas: [ [Object], [Object] ] } }

How would I go on and map this in a way where the unique object keys become X number of values inside an array with its combined data values matching that key. Heres an example of what I'm trying to achieve

    const array = [
      {
        symbol: 'star',
        data: [
          { apples: [[Object], [Object]] },
          { oranges: [[Object], [Object]] },
          { bananas: [[Object], [Object]] },
        ],
      },
      {
        symbol: 'circle',
        data: [{ apples: [[Object]] }, { oranges: [[Object]] }],
      },
    ];
 

I'm assuming it would be using a reduce function and getting the keys of current value index and mapping through the keys, while checking if key exists in accumlator if not add it. Haven't reached more far than this implementation/logic

Upvotes: 0

Views: 75

Answers (1)

IT goldman
IT goldman

Reputation: 19485

Yes you said it.

const array = [ 
  {
    star: { apples: [ {flag : true}, {flag : true} ] },
    circle: { apples: [ {flag : true} ] }
  },
  {
    star: { oranges: [ {flag : true}, {flag : true} ] },
    circle: { oranges: [ {flag : true} ] }
  },
  { 
    star: { bananas: [ {flag : true}, {flag : true} ] } 
  }
]

var result = Object.values(array.reduce (function (agg, obj_shapes) {
  Object.keys(obj_shapes).forEach(function (shape) {
    var fruits = obj_shapes[shape]
    agg[shape] = agg[shape] || {
      symbol: shape,
      data: []
    }
    agg[shape].data.push(fruits)
  })
  return agg;
}, {}));

console.log(result)
.as-console-wrapper {max-height: 100% !important}

Upvotes: 1

Related Questions