我们如何在以下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",
}
]
}
答案 0 :(得分: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);
}
}
答案 1 :(得分: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"]