所以我有这些数据:
const data = [
{
product_name: 'BMW',
year: '1982'
},
{
product_name: 'BMW',
year: '1998'
},
{
product_name: 'LandRover',
year: '1982'
},
{
product_name: 'BMW',
year: '1982'
},
{
product_name: 'LandRover',
year: '1985'
},
{
product_name: 'LandRover',
year: '1981'
}
]
使用普通的 javascript,我需要将数据过滤到这样的数组中:
[
{
name: 'BMW',
data: [1982, 1998, 1982]
},
{
name: 'LandRover',
data: [1982, 1985, 1981]
}
]
有人可以帮忙吗?不确定解决这个问题的最佳方法。
非常感谢
最佳答案
您可以reduce将数据发送到Map ,得到Map values iterator ,然后 spread它到一个数组:
const data = [{"product_name":"BMW","year":"1982"},{"product_name":"BMW","year":"1998"},{"product_name":"LandRover","year":"1982"},{"product_name":"BMW","year":"1982"},{"product_name":"LandRover","year":"1985"},{"product_name":"LandRover","year":"1981"}];
const result = [...data.reduce((m, o) => {
// if map doesn't have the product_name, init the object and add to map
m.has(o.product_name) || m.set(o.product_name, {
name: o.product_name,
data: []
});
// get the product object, and add the year
m.get(o.product_name).data.push(o.year);
return m;
}, new Map()).values()]; // get the map values, and spread to an array
console.log(result);
关于Javascript将数组过滤到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47790878/