我正在尝试获取一个对象名称数组,这些对象的 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/