سؤال

I have this code:

    var dictionary=[
            apple={name:"apple",pos:"noun",d:"",c:["fruit"]},
            banana={name:"banana",pos:"noun",d:"",c:["fruit"]}
    ];

How could I access one of the objects in the array by using a string of its name. In the way that you could access an object as

     object['propertyName']

is there a way to do something similar with an array? I want to access it in a way like

    dictionary["apple"].pos 
    //Want to return "noun"

Is there a simple way to do something like that with an array, and if not is there an alternative method that I could use?

هل كانت مفيدة؟

المحلول

The way you're generating your dictionary s wrong; it's syntactically valid, but it's almost certainly not what you intended to do. It's not binding the key apple to that object. Rather, it's defining an implicit (global) variable named apple and assigning the object to that, as well as the first element of the array.

Try this:

var dictionary= {
    apple: {name:"apple",pos:"noun",d:"",c:["fruit"]},
    banana: {name:"banana",pos:"noun",d:"",c:["fruit"]}
};

console.log(dictionary["apple"].pos); // "noun"

// This also works:
console.log(dictionary.apple.pos);    // "noun"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top