james james - 4 months ago 20
Javascript Question

how to reach index of json items using javascript?

I have a json file like this:

{"news": [{name:"abc",type:"qwe"},{name:"bnmb",type:"yas"},{name:"lkj",type:"tyr"},...]}

How can I get the index of the object?

For example: for the type=="qwe", I want to get index 0.
and also I want to reach name property of qwe.


If you have an Object literal as you mentioned (perhaps on that phase you have already parsed the JSON I'm guessing).

You can simply cycle through your object until you've find the key your looking for, a sample code would go like this:

var json = {"news": [{name:"abc",type:"qwe"},{name:"bnmb",type:"yas"},{name:"lkj",type:"tyr"}]};
var index, property;

for (var i = 0; i < json.news.length; i++) {    
    for (var prop in json.news[i]) {
      if (json.news[i].hasOwnProperty(prop) && json.news[i][prop] == 'qwe') {
        index = i;
        property = prop;

console.log(index); //=> 0
console.log(property); //=> 'type'