gpt4 book ai didi

javascript - 将对象数组中的特定属性返回到新对象中

转载 作者:行者123 更新时间:2023-11-28 14:07:08 27 4
gpt4 key购买 nike

我有一个对象数组,我想要的是从中复制所有对象,但使用特定属性而不是所有属性。例如我有一个名为 cart 的对象

cart = [
{ id: 1, name: 'makeup', price: 200, qty: 1 },
{ id: 2, name: 'gloves', price: 300, qty: 2 },
{ id: 3, name: 'sanitizer', price: 400, qty: 3 },
{ id: 4, name: 'book', price: 100, qty: 1 },
{ id: 5, name: 'hairs', price: 250, qty: 4 },
{ id: 6, name: 'soap', price: 50, qty: 5 },
{ id: 7, name: 'shampoo', price: 700, qty: 1 },
]

我只想提取 idqty属性到新的对象数组。我该怎么做呢。我已经尝试过了 products=cart.map(prod=>prod.id, prod.qty)但这似乎不起作用。预先感谢伸出的援助之手

最佳答案

您可以Array.prototype.map()Array.prototype.reduce()遍历整个数组,并且只返回您想要的值。

const cart = [
{ id: 1, name: 'makeup', price: 200, qty: 1 },
{ id: 2, name: 'gloves', price: 300, qty: 2 },
{ id: 3, name: 'sanitizer', price: 400, qty: 3 },
{ id: 4, name: 'book', price: 100, qty: 1 },
{ id: 5, name: 'hairs', price: 250, qty: 4 },
{ id: 6, name: 'soap', price: 50, qty: 5 },
{ id: 7, name: 'shampoo', price: 700, qty: 1 },
]
console.log( cart.map( elem => ({id:elem.id, qty : elem.qty})))

关于javascript - 将对象数组中的特定属性返回到新对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60973143/

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