我有以下JSON数组:
{
"list": [{
"name": "Assignment",
"id": 67,
"template": 0,
"children": [{
"assignmentnumber": 1000,
"fromCountry": "Sweden",
"toCountry": "Spain",
"fromCity": "Stockholm",
"toCity": "Madrid"
}, {
"assignmentnumber": 15678,
"fromCountry": "Sweden",
"toCountry": "Germany",
"fromCity": "Stockholm",
"toCity": "Berlin"
}, {
"assignmentnumber": 10001,
"fromCountry": "Sweden",
"toCountry": "United Kingdom",
"fromCity": "Stockholm",
"toCity": "London"
}]
}, {
"name": "Valuation form",
"id": 36,
"template": 0,
"children": [15678]
}, {
"name": "Claim",
"id": 12,
"template": 0,
"children": [1000, 10001]
}]
}
我需要从仅包含'name'元素的数组中提取一个新数组。我试过lodash,但无法弄清楚如何正确使用它。
任何可以告诉我如何做到这一点的人?
答案 0 :(得分:0)
您可以使用本机Array API在没有lodash的情况下执行此操作。
const obj = { /* The JSON in your question */ };
const names = obj.list.map(item => item.name);
Array.map()
接受一个函数,并在数组的每个项目上调用该函数,返回一个包含每个项目结果的新数组。
答案 1 :(得分:0)
地图是其他人所说的最佳方式。另一种方法是使用forEach循环,特别是如果你想使用它们。
var children = obj.children;
var array_of_names;
children.forEach(function (item)){
array_of_names.push(item.name);
//... Do more operations for each item
}