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:
JavaScript
x
7
1
{
2
3:
3
{
4
"3_4": "answer1"
5
}
6
}
7
I pushed them into an array, so I get this:
JavaScript
1
2
1
[{3:{"3_04":"answer1"}},{3:{"3_10":"other answer"}},{6:{"6_01":"Eos ut numquam dolor"}}]
2
I need to unify this so the objects with same key (i.e. 3) would merge into one, so I get:
JavaScript
1
12
12
1
{
2
3:
3
{
4
"3_04": "answer1",
5
"3_10": "other answer"
6
}
7
6:
8
{
9
"6_01": "Eos ut numquam dolor"
10
}
11
}
12
I can’t change the data structure , so this is what I came up so far which seems to work:
JavaScript
1
28
28
1
const unionSurveyTextAnswersArrayKeys = [];
2
const unionSurveyTextAnswersArray = [];
3
this.tempSurveyTextAnswersArray.map(answerItem => {
4
if (!unionSurveyTextAnswersArrayKeys.includes(Object.keys(answerItem)[0])) {
5
unionSurveyTextAnswersArray.push([
6
Object.keys(answerItem),
7
answerItem[Object.keys(answerItem)]
8
]);
9
unionSurveyTextAnswersArrayKeys.push(Object.keys(answerItem)[0]);
10
} else {
11
unionSurveyTextAnswersArray.map(unionAnswerItem => {
12
if (unionAnswerItem[0][0] === Object.keys(answerItem)[0]) {
13
unionAnswerItem[1] = Object.assign(
14
{},
15
unionAnswerItem[1],
16
answerItem[Object.keys(answerItem)]
17
);
18
}
19
});
20
}
21
});
22
let surveyAnswers = this.submitData || {};
23
unionSurveyTextAnswersArray.map(item => {
24
const [key, value] = item;
25
surveyAnswers = Object.assign({}, surveyAnswers, { [key]: value });
26
});
27
this.submitData = surveyAnswers;
28
but this is really complicated and hard to read. So I want to know if someone knows a better/simpler way to do this?
Advertisement
Answer
You can try with this code:
JavaScript
1
12
12
1
this.tempSurveyTextAnswersArray = [{3:{"3_04":"answer1"}},{3:{"3_10":"other answer"}},{6:{"6_01":"Eos ut numquam dolor"}}];
2
3
const boh = this.tempSurveyTextAnswersArray.reduce((accumulator, currentValue, index, array) => {
4
for (const key in currentValue) {
5
const element = currentValue[key];
6
7
accumulator[key] = { element, accumulator[key] };
8
9
}
10
return accumulator;
11
}, {});
12