Skip to content

unify objects from array to a bigger object

My english is not really good and it is hard to explain what I want in the title, maybe this will help: I have some small data objects which I get from answers of a form. Something like this:

{
  3:
    {
      "3_4": "answer1"
    }
}

I pushed them into an array, so I get this:

[{3:{"3_04":"answer1"}},{3:{"3_10":"other answer"}},{6:{"6_01":"Eos ut numquam dolor"}}]

I need to unify this so the objects with same key (i.e. 3) would merge into one, so I get:

{
   3:
     {
       "3_04": "answer1",
       "3_10": "other answer"
     }
   6:
     {
        "6_01": "Eos ut numquam dolor"
     }
 }

I can’t change the data structure , so this is what I came up so far which seems to work:

const unionSurveyTextAnswersArrayKeys = [];
const unionSurveyTextAnswersArray = [];
this.tempSurveyTextAnswersArray.map(answerItem => {
  if (!unionSurveyTextAnswersArrayKeys.includes(Object.keys(answerItem)[0])) {
    unionSurveyTextAnswersArray.push([            
        Object.keys(answerItem),
        answerItem[Object.keys(answerItem)]
    ]);
    unionSurveyTextAnswersArrayKeys.push(Object.keys(answerItem)[0]);
  } else {
    unionSurveyTextAnswersArray.map(unionAnswerItem => {
      if (unionAnswerItem[0][0] === Object.keys(answerItem)[0]) {
        unionAnswerItem[1] = Object.assign(
            {},
            unionAnswerItem[1],
            answerItem[Object.keys(answerItem)]
        );
      }
    });
  }
});
let surveyAnswers = this.submitData || {};
unionSurveyTextAnswersArray.map(item => {
  const [key, value] = item;
  surveyAnswers = Object.assign({}, surveyAnswers, { [key]: value });
});
this.submitData = surveyAnswers;

but this is really complicated and hard to read. So I want to know if someone knows a better/simpler way to do this?

Answer

You can try with this code:

this.tempSurveyTextAnswersArray = [{3:{"3_04":"answer1"}},{3:{"3_10":"other answer"}},{6:{"6_01":"Eos ut numquam dolor"}}];

const boh = this.tempSurveyTextAnswersArray.reduce((accumulator, currentValue, index, array) => {
  for (const key in currentValue) {
    const element = currentValue[key];

    accumulator[key] = { ...element, ...accumulator[key] };

  }
  return accumulator;
}, {});