I have an array with several objects some have the same keys (Question and QuestionId), for example:
var jsonData = [
{
Question: "Was the training useful?",
QuestionId: 1,
myData: [{ name: 'No', value: 1 }] },
{
Question: "Was the training useful?",
QuestionId: 1 ,
myData: [{ name: 'Yes', value: 1 }]
}];
How can I combine these objects into one, expected output:
var jsonData = [
{
Question: "Was the training useful?",
QuestionId: 1,
myData: [{ name: 'No', value: 1 },
{ name: 'Yes', value: 1 }]
}];
CodePudding user response:
var jsonData = [{
Question: "Was the training useful?",
QuestionId: 1,
myData: [{
name: 'No',
value: 1
}]
},
{
Question: "Was the training useful?",
QuestionId: 1,
myData: [{
name: 'Yes',
value: 1
}]
}
];
const result = Object.values(jsonData.reduce((acc, obj) => {
if (!acc[obj.QuestionId]) {
acc[obj.QuestionId] = obj;
} else {
acc[obj.QuestionId].myData = acc[obj.QuestionId].myData.concat(obj.myData);
}
return acc;
}, {}));
console.log(result);
CodePudding user response:
function mergeData(data) {
const acc = {}
data.forEach(x => {
const id = x.QuestionId
if (!acc[id]) acc[id] = x
else acc[id].myData = acc[id].myData.concat(x.myData)
})
return Object.values(acc)
}
CodePudding user response:
You can use forEach to create an object where the keys are the question IDs and then use forEach again on Object.keys to transfer the values from that object to a new array.
var jsonData = [{
Question: "Was the training useful?",
QuestionId: 1,
myData: [{ name: 'No', value: 1 }]
}, {
Question: "Was the training useful?",
QuestionId: 1 ,
myData: [{ name: 'Yes', value: 1 }]
}];
var temp = {};
jsonData.forEach(x=>{
if(!temp[x.QuestionId]) {temp[x.QuestionId] = x;}
else {temp[x.QuestionId].myData.push(x.myData);}
});
var arr = [];
Object.keys(temp).forEach(x=>{arr.push(temp[x]);});
console.log(arr);