1

我目前正在尝试遍历一个看起来像这样的 JSON 对象:

"coupons":{
    "item1":{
         "id":"155",
         "name":"First Item",
         "value":-5199.6
    },
    "item2":{
         "id":"255",
         "name":"Second Item",
         "value":-424.91
    }
}

我想返回每个项目 id 的值。我怎样才能做到这一点?

我正在用 JS 编程。

谢谢!

4

5 回答 5

1
var coupons = {
    "item1":{
         "id":"155",
         "name":"First Item",
         "value":-5199.6
    },
    "item2":{
         "id":"255",
         "name":"Second Item",
         "value":-424.91
    }
}

var ids = [];
for(var item in coupons) {
    ids.push(coupons[item]['id']);
}

console.log(ids);
于 2012-11-10T21:38:02.720 回答
0

You can use DefiantJS (http://defiantjs.com), which enables you to search a JSON structure with XPath queries. This lib extends the global object JSON with the method "search" and returns an array with the matches, if any (empty array, i no matches were found).

XPath is a standardised query language and pretty easy the grasp. Here is a testing tool with examples; http://defiantjs.com/#xpath_evaluator

Check out this working fiddle;
http://jsfiddle.net/hbi99/Yc6cc/

var data = {
    ...
},
res = JSON.search( data, '//*[id]' ),
str = '';

for (var i=0; i<res.length; i++) {
    str += res[i].id +' : '+ res[i].name +'<br/>';
}

document.getElementById('output').innerHTML = str;
于 2014-01-09T03:00:24.300 回答
0
var obj = { 'json...' };

for (var key in obj)
{
    var item = obj[key];
    alert("id is " + item.id);
}

您可以使用var .. in obj语法来迭代任何对象的属性(或关联索引;在 JS 中相同)。始终注意您了解正在迭代的对象,因为某些对象(例如数组)具有您希望避免迭代的其他属性。

于 2012-11-10T21:37:17.400 回答
0

每个coupons[k]都是项目,你可以使用coupons[k].id

var coupons = {
    "item1":{
         "id":"155",
         "name":"First Item",
         "value":-5199.6
    },
    "item2":{
         "id":"255",
         "name":"Second Item",
         "value":-424.91
    }
}

for(var k in coupons){
      console.log(coupons[k].id);

}
于 2012-11-10T21:37:36.917 回答
0

I would suggest something like:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var dataset = {
                "coupons":{
                    "item1":{
                         "id":"155",
                         "name":"First Item",
                         "value":-5199.6
                    },
                    "item2":{
                         "id":"255",
                         "name":"Second Item",
                         "value":-424.91
                    }
                }
            }

$(document).ready(function(){

    $.each(dataset.coupons, function(i, item) {
        $("#data").append('<p>' + item.id + '</p>'); 
        $("#data").append('<p>' + item.name + '</p>'); 
        $("#data").append('<p>' + item.value + '</p>'); }
    );

});

</script>
<div id="contentC"></div>
于 2012-11-10T21:44:30.923 回答