gpt4 book ai didi

Javascript对象,访问相关键

转载 作者:行者123 更新时间:2023-12-04 02:06:16 25 4
gpt4 key购买 nike

我有以下 Javascript 对象:

var icecreams = [{
name: 'vanilla',
price: 10,
rating: 3
}, {
name: 'chocolate',
price: 4,
rating: 8
}, {
name: 'banana',
price: 1,
rating: 1
}, {
name: 'greentea',
price: 5,
rating: 7
}, {
name: 'moosetracks',
price: 6,
rating: 2
}, ];

我需要访问对象每个部分中的“相关属性”(不确定确切的术语)。例如,如果我的名字是“vanilla”,我需要访问 10 的“价格”和 3 的“评级”。有没有办法在不改变对象结构的情况下做到这一点?可能使用 this

最佳答案

您可以使用 Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var vanilla = icecreams.filter(function(o){
return o.name === 'vanilla'
});
//As filter return's an array you need to use index thus [0] to access first element of array
console.log(vanilla[0].price);
console.log(vanilla[0].rating);

关于Javascript对象,访问相关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35323296/

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