Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this array:

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});

is it possible to do get the value or a specific element by knowing the name ?

something like this:

arr['k2'].value

or

arr.get('k1')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
127 views
Welcome To Ask or Share your Answers For Others

1 Answer

I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});

var found = arr.filter(function(item) { return item.name === 'k1'; });

console.log('found', found[0]);
Check the console.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...