Javascript对象,访问相关键

时间:2016-02-10 18:37:52

标签: javascript

我有以下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和"等级"有没有办法在不改变对象结构的情况下做到这一点?可能使用this

5 个答案:

答案 0 :(得分:5)

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

  

filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

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);

答案 1 :(得分:4)

在ECMAScript 2015中,您可以在数组中找到对象:

var vanilla = icecreams.find(o => o.name === 'vanilla')
console.log(vanilla.price);
console.log(vanilla.rating);

ES5类比:

var vanilla = icecreams.reduce(function(r, o) {
    return r || (o.name === 'vanilla' ? o : undefined);
}, undefined);
console.log(vanilla.price);
console.log(vanilla.rating);

答案 2 :(得分:0)

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}, ];
var found = {};

for(i in icecreams){
      if(icecreams[i].name == 'vanilla'){
             found = icecreams[i];
             break;
      }
}
console.log('Price: ' + found.price);
console.log('Price: ' + found.rating);

答案 3 :(得分:0)

如果你能控制变量冰淇淋的结构,我会使用一个oject而不是一个数组来保存这些味道。这样可以通过名称轻松访问值。

var icecream = {
    vanilla: {price: 10, taring: 3},
    banana: {price: 1, taring: 1},
    greentea: {price: 5, taring: 7},
    moosetracks: {price: 6, taring: 2}
};

或者如果他们来自AJAX(或其他动态来源),我可能会调整它们:

//Assume icecream follows your original structure.
function tranformFlavors(flavors) {
    var flavorObj = {};
    flavors.forEach(item){
        flavorObj[item.name] = item;
        delete flavorObj[item.name].name;
    }
    return flavorObj;
}

icecream = transformFlavors(icecream);

答案 4 :(得分:-1)

如果您使用的是ES5,则可以使用下划线或lodash。

http://underscorejs.org/#find 要么 http://underscorejs.org/#filter 要么 http://underscorejs.org/#where 要么 http://underscorejs.org/#findWhere