这是我的输出查询:
array = [
0: {brand: "Samsung", phone_unit: "J7 pro"}
1: {brand: "Samsung", phone_unit: "S9"}
2: {brand: "Samsung", phone_unit: "S7"}
3: {brand: "Iphone", phone_unit: "iphone 6s"}
4: {brand: "Iphone", phone_unit: "iphone X"}
]
这就是我想发生的事情
array = [
0: {
brand: "Samsung",
phone_unit: ["J7 pro", "S9", "S7"]
}
1: {
brand: "Iphone",
phone_unit: ["iphone 6S", "iphone X"]
}
]
如何使用 map 或 ES6 javascript
答案 0 :(得分:0)
您可以通过将数组缩小为由brand
分组的对象,然后调用Object.values
以获得最终数组来实现:
const array = [
{brand: "Samsung", phone_unit: "J7 pro"},
{brand: "Samsung", phone_unit: "S9"},
{brand: "Samsung", phone_unit: "S7"},
{brand: "Iphone", phone_unit: "iphone 6s"},
{brand: "Iphone", phone_unit: "iphone X"}
];
const result = Object.values(array.reduce((acc, {brand, phone_unit}) => {
if (!(brand in acc)) acc[brand] = {brand, phone_unit: [phone_unit]};
else acc[brand].phone_unit.push(phone_unit);
return acc;
}, {}));
console.log(result);