0

I have such an object

data: {
      dataFirst: { 
        Food: [ {id: 536131, name: "option1", }]
      },       
      dataSecond: { 
        Autos: [{id: 678, name: 'option1'}],
        Houses: [
          {id: 6876, name: "option1"},
          {id: 6876, name: "Placed App"},
        ],
        Phones: [
          {id: 672, name: "option1"},
          {id: 97249, name: "Placed},
        ],
        Food: [
          {id: 772, name: "option1"},
          {id: 6777, name: "Placed},
        ], 
      }
    }  

The problem is, that I may have same data in dataFirst and dataSecond, for examle 'Food', I have 2 array objects that contains different data but I need to make it one object 'Food' with the data from 2 of them, from the dataFirst 'Food' and dataSecond 'Food'. I had such a code:

export const parser = ({ data }) => {
  const result = Object.values(data).reduce((prev, topicsGroup) => {
    Object.assign(prev, topicsGroup);
    return prev;
  }, {});
  return result;
}

but this code doesn't unite 2 'Food' objects but returns data only from the dataFirst 'Food' object wihout second one.

1 Answer 1

2

You can iterate through all values of your main data object with Object.values(data) and combine them with reduce by concatenating arrays corresponding to common keys:

let data = {
  dataFirst: {
    Food: [{
      id: 536131,
      name: "option1",
    }]
  },
  dataSecond: {
    Autos: [{
      topicId: 678,
      name: 'option1'
    }],
    Houses: [{
        topicId: 6876,
        name: "option1"
      },
      {
        topicId: 6876,
        topicName: "Placed App"
      },
    ],
    Phones: [{
        topicId: 672,
        name: "option1"
      },
      {
        topicId: 97249,
        name: "Placed"
      },
    ],
    Food: [{
        topicId: 772,
        name: "option1"
      },
      {
        topicId: 6777,
        name: "Placed"
      },
    ],
  }
};


let res = Object.values(data).reduce((acc, curr) => {
  Object.entries(curr).forEach(([k, v]) => {
    if (k in acc) acc[k] = acc[k].concat(v);
    else acc[k] = v;
  });
  return acc;
}, {});

console.log(res);

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

Comments

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.