我有一个看起来像这样的数组:
[
{ id: 9,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 10,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 11,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 12,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 13,
email: 'user@example.com',
product: 'joystick',
date: 2019-03-11 },
etc...............
]注意数组中对象的键是静态的,但是值是动态的,除了电子邮件=>,电子邮件是静态的。
数组的长度是动态的,不是静态的,所以对象的数量是动态的。
如何过滤这个数组以获得如下结果
{
email: 'user@example.com', // email here is static AKA is known
handbag: 4, // keys here , not just keys they are the values of keys in objects in array , and i want to use them like has access to them
smartphone: 1,
joystick: 1,
etc.......
}因此,输出到客户端的最后一行如下:
你有4种手袋产品,1种手柄产品,1种智能手机产品等.
备注我不知道最后一个对象的长度,也不知道数组的长度,除了电子邮件之外,所有数据都是动态的。
这个问题,我觉得有点挑战。
发布于 2019-03-12 19:03:09
你可以这样减少:
const data = [{ id: 9,email: 'user@example.com',product: 'handbag',date: 2019-03-11 },{ id: 10,email: 'user@example.com',product: 'handbag',date: 2019-03-11 },{ id: 11,email: 'user@example.com',product: 'handbag',date: 2019-03-11 },{ id: 12,email: 'user@example.com',product: 'handbag',date: 2019-03-11 },{ id: 13,email: 'user@example.com',product: 'joystick',date: 2019-03-11 }];
const result = data.reduce((acc, {product}) => (acc[product] = (acc[product]||0)+1, acc),
{ email: data[0].email });
console.log(result);
const phrase = `${result.email} you have in your account ${
Object.entries(result).map(([k, v]) => k!=="email" && `${v} ${k}${v>1?"s":""}`)
.filter(Boolean).join(" and ")
}`;
console.log(phrase);
代码的第一部分使用reduce和逗号运算符,以便在分配给acc[product]之后返回所谓的累加器。
当||0还不存在时,acc[product]是必需的,然后计数必须从0开始。
{ email: data[0].email }是reduce构建的累加器的初始值。它是将用其他属性扩展的对象的开始。
发布于 2019-03-12 19:04:27
使用“约简”将数组降为对象。
const items = [
{ id: 9,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 10,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 11,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 12,
email: 'user@example.com',
product: 'handbag',
date: 2019-03-11 },
{ id: 13,
email: 'user@example.com',
product: 'joystick',
date: 2019-03-11 }
]
let result = items.reduce((obj, itm) => {
obj.email = itm.email
obj[itm.product] = obj[itm.product] + 1 || 1
return obj
}, {})
let str = []
Object.entries(result).forEach(entry => {
if(entry[0] == 'email') return
str.push(`${entry[1]} products of ${entry[0]}`)
})
document.body.innerHTML = `You have ${str.join(' and ')}`
https://stackoverflow.com/questions/55128853
复制相似问题