1

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?

yangsunny
  • 656
  • 5
  • 13
  • 32
  • Does this answer your question? [How to deep merge instead of shallow merge?](https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge) – User863 Jan 19 '21 at 13:39
  • Does this answer your question? [Merge two array of objects based on a key](https://stackoverflow.com/questions/46849286/merge-two-array-of-objects-based-on-a-key) – Heretic Monkey Jan 19 '21 at 13:52
  • Combine the two questions above... – Heretic Monkey Jan 19 '21 at 13:52

1 Answers1

1

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;
}, {});
AlTheLazyMonkey
  • 1,190
  • 1
  • 8
  • 20