Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - json index of property value

I need to get the index of the json object in an array whose by the objects id

here is the example code

var list = [ { _id: '4dd822c5e8a6c42aa70000ad',
    metadata: 
     { album: 'American IV: Man Comes Around',
       song: 'Hurt',
       coverart: 'http://images.mndigital.com/albums/044/585/435/m.jpeg',
       artist: 'Johnny Cash',
       length: 216,
       mnid: '44585439' } },
  { _id: '4dd80b16e8a6c428a900007d',
    metadata: 
     { album: 'OK Computer (Collector's Edition)',
       song: 'Paranoid Android',
       coverart: 'http://images.mndigital.com/albums/026/832/735/m.jpeg',
       artist: 'Radiohead',
       length: 383,
       mnid: '26832739' } },
  { _id: '4dd68694e8a6c42c80000479',
    metadata: 
     { album: 'The Presidents Of The United States Of America: Ten Year Super Bonus Special Anniversary Edition',
       song: 'Lump',
       coverart: 'http://images.mndigital.com/albums/011/698/433/m.jpeg',
       artist: 'The Presidents Of The United States Of America',
       length: 134,
       mnid: '11698479' } }
]

then pseudo code

 var index_of  = list.indexOf("4dd80b16e8a6c428a900007d");

obviously that is not gonna work but I wonder if there is anyway to do this without looping to find the index ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
var i = list.length;
while( i-- ) {
    if( list[i]._id === '4dd80b16e8a6c428a900007d' ) break;
}

alert(i);  // will be -1 if no match was found

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...