gpt4 book ai didi

javascript - 当 option.amount 等于零时获取数组中对象的名称

转载 作者:行者123 更新时间:2023-12-03 07:18:10 26 4
gpt4 key购买 nike

我正在尝试获取一个对象名称数组,这些对象的 options.amount 都为零。谢谢你的时间。这是我尝试过的:

let variants = [        
{
name: 'extra',
options: [
{
name: 'meat',
price: 3,
amount: 0
},
{
name: 'cheese',
price: 1,
amount: 0
}
]
},
{
name: 'sauce',
options: [
{
name: 'ketchup',
price: 2,
amount: 1
},
{
name: 'mayo',
price: 1,
amount: 0
}
]
}
];

//Expected output = ['extra']

let arrayOfOptionsNames = variants.map(x => x.options.filter(y => y.amount === 0 ? x.name : 0))
console.log(arrayOfOptionsNames)

最佳答案

您可以使用 Array.prototype.filter()Array.prototype.every() 方法来获得结果。 Every 方法测试数组的每个元素是否通过给定回调函数的测试并返回 bool 值。

const variants = [
{
name: 'extra',
options: [
{
name: 'meat',
price: 3,
amount: 0,
},
{
name: 'cheese',
price: 1,
amount: 0,
},
],
},
{
name: 'sauce',
options: [
{
name: 'ketchup',
price: 2,
amount: 1,
},
{
name: 'mayo',
price: 1,
amount: 0,
},
],
},
];
const ret = variants
.filter((x) => x.options.every((y) => y.amount === 0))
.map((x) => x.name);
console.log(ret);

关于javascript - 当 option.amount 等于零时获取数组中对象的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64826321/

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