-2

我们如何在下面的 JSON 对象数组中列出属性的值(例如,“ObjectPropertyTwo”)?

    {
    "KeyOne": [
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
    ],
    "KeyTwo": [
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
    ],
    "KeyThree": [
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        },
        {
            "ObjectPropertyOne": "value",
            "ObjectPropertyTwo": "value",
            "ObjectPropertyThree": "value",
            "ObjectPropertyFour": "value",
        }
    ]
}
4

2 回答 2

2

怎么样:

for (var key in data) { //data being the object
    for (var i = 0; i < data[key].length; i++) {
        console.log(data[key][i].ObjectPropertyTwo);
    }
}

演示:http: //jsfiddle.net/tymeJV/csFms/

于 2013-09-27T16:33:35.043 回答
1
function listNestedProperties(object, property) {
  return Object.keys(object).reduce(function(memo, key) {
    object[key].forEach(function(o2) {
      memo.push(o2.ObjectPropertyTwo);
    });
    return memo;
  }, []);
}

listNestedProperties(yourObject, 'ObjectPropertyTwo');
// => ["value", "value", "value", "value", "value", "value", "value", "value", "value"]
于 2013-09-27T16:44:06.900 回答