0

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

1 Answer 1

1

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}

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick thank you! I was doing the indexing on the agg apparently wrong. If one would want to make data array into an object such as data: {oranges:{},bananas:{}..etc} assuming that the data inside doesnt have the same key and 1 of each only

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.