当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript object, access related keys

问题描述:

I have the following Javascript object:

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

}, ];

I need to access the "related properties" (not sure of the exact terminology) in each section of the object. For example, if I am given the name "vanilla," I need to access a "price" of 10 and "rating" of 3. Is there a way to do this without changing the object's structure? Possibly using this?

网友答案:

You can use 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);
网友答案:

In ECMAScript 2015 you can find object in your array like this:

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

ES5 analogy:

var vanilla = icecreams.reduce(function(r, o) {
    return r || (o.name === 'vanilla' ? o : undefined);
}, undefined);
console.log(vanilla.price);
console.log(vanilla.rating);
网友答案:
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);
网友答案:

if you have control over the structure of the variable icecream, I'd uses an oject instead of an array to hold the flavors. This makes it simple to access the values by name.

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

Or I'd probably adapt them if they came via AJAX (or another dynamic source):

//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);
网友答案:

If you're using ES5, you can use underscore or lodash for this.

http://underscorejs.org/#find or http://underscorejs.org/#filter or http://underscorejs.org/#where or http://underscorejs.org/#findWhere

分享给朋友:
您可能感兴趣的文章:
随机阅读: