I'm not familiar with javascript and I don't know how to search for this problem. Here I've explained briefly about my problem. Below is the data from which I've to find out the similar entries in the data and combine them as one object. This is my data:
var myArr = [{
"Company": "Samsung",
"model": "Galaxy S2",
"screen_size": "5.5"
},
{
"Company": "Samsung",
"model": "Galaxy S3",
"screen_size": "5.5"
},
{
"Company": "Samsung",
"model": "Galaxy S4",
"screen_size": "5.5"
},
{
"Company": "Xiaomi",
"model": "Redmi 2",
"screen_size": "4.7"
},
{
"Company": "Xiaomi",
"model": "Redmi 4",
"screen_size": "5"
},
{
"Company": "Xiaomi",
"model": "Redmi Note 4",
"screen_size": "5.5"
}
]
I want to combine all the duplicate entries in the array. So, my outcome of this data should be like this:
[{
"Company": "Samsung",
"models": [{
"Galaxy S2": {
"screen_size": "5.5"
}
}, {
"Galaxy S3": {
"screen_size": "5.6"
}
}, {
"Galaxy S4": {
"screen_size": "5.7"
}
}]
}, {
"Company": "Xiaomi",
"models": [{
"Redmi 2": {
"screen_size": "4.7"
}
}, {
"Redmi 4": {
"screen_size": "5"
}
}, {
"Redmi Note 4": {
"screen_size": "5.5"
}
}]
}]
Somebody, please help me.
You can group your object using array#reduce
on the Company
key in an object and extract all the values using Object.values()
.
var myArr=[{ "Company": "Samsung", "model": "Galaxy S2", "screen_size": "5.5" }, { "Company": "Samsung", "model": "Galaxy S3", "screen_size": "5.5" }, { "Company": "Samsung", "model": "Galaxy S4", "screen_size": "5.5" }, { "Company": "Xiaomi", "model":"Redmi 2", "screen_size": "4.7" }, { "Company": "Xiaomi", "model": "Redmi 4", "screen_size": "5" }, { "Company": "Xiaomi", "model": "Redmi Note 4", "screen_size": "5.5" } ],
result = Object.values(myArr.reduce((r,o) => {
r[o.Company] = r[o.Company] || {'Company': o.Company, 'Models' : []};
r[o.Company]['Models'].push({[o.model]:{'screen_size' : o.screen_size}});
return r;
}, {}));
console.log(result);