gpt4 book ai didi

javascript - 如何使用javascript将对象数组的重复元素合并为一个

转载 作者:行者123 更新时间:2023-11-29 23:28:21 26 4
gpt4 key购买 nike

我对javascript不熟悉,也不知道如何搜索这个问题。在这里,我简要解释了我的问题。下面是我必须从中找出数据中相似条目并将它们组合为一个对象的数据。这是我的数据:

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"
}
]

我想合并数组中所有重复的条目。所以,我的这个数据的结果应该是这样的:

[{
"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"
}
}]
}]

有人,请帮助我。

最佳答案

您可以在对象的 Company 键上使用 array#reduce 对对象进行分组,并使用 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);

关于javascript - 如何使用javascript将对象数组的重复元素合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48237301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com