我需要从复杂的javascript对象中提取字符串属性。
以下是我的情景:
for (var key in results) {
console.log(results[key]);
...results[key] is an object that returns few arrays and properties
...i need to capture an array inside named "all_names"
...again loop through all the objects in the array "all_names"
...all the objects have a property name called "first_name"
...i need to capture the "first_name" that have the value "Paul"
}
示例数据:
在console.log之后(结果[key]);
“all_names”:数组[7]
地址:“一些地址”
org_number:“TV146”
然后循环“all_names”
“first_name”:“保罗”
“last_name”:“汉森”
捕捉“保罗”
请帮忙。
答案 0 :(得分:1)
只要有数组属性,就可以使用for (var x in arr)
和结果一样。如果没有示例对象,请从您的描述中获得:
results[].all_names[].first_name
给出了
for (var key in results)
{
//...results[key] is an object that returns few arrays and properties
//...I need to capture an array inside named "all_names"
//...loop through all the objects in the array "all_names"
for (var namekey in results[key].all_names)
{
// all the objects have a property name called "first_name"
// ...i need to capture the "first_name" that have the value "Paul"
if (results[key].all_names[namekey].first_name == 'Paul') {
// will always be "Paul"
console.log(results[key].all_names[namekey].first_name);
//perhaps: console.log(key);
}
}
}
答案 1 :(得分:1)
for (var key in results) {
results[key]["all_names"].forEach(function (obj) {
if (obj["first_name"] === "Paul") {
// this is Paul
}
});
}