I have an array of objects, the objects are the same but with different values. What I need is to generate a new object but concatenating the values of the same property.
This is the array:
interface Test {
group: string,
model: any
}
let dataObj: Test[] = [
{
"group":"car",
"model":{
"test":"test1",
"data":"data1"
}
},
{
"group":"car",
"model":{
"test":"test2",
"data":"data2"
}
}
]
This is what I do:
let result = {
visualize: {}
}
dataObj.forEach((item: Test) => {
const { group, model } = item
result.visualize[group] = {
model
}
})
This is what I get:
{"visualize":{"car":{"model":{"test":"test2","data":"data2"}}}}
This is what I need:
{"visualize":{"car":{"model":{"test":"test1,test2","data":"data1,data2"}}}}
2
Answers
You can use Array.reduce() to iterate over the dataObj array and accumulate the result in the result object.
And then the output should be :
You need to add to the same group.