我有以下 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,但不知道如何正确使用它。
谁能告诉我如何做到这一点?
最佳答案
您应该使用map
方法,该方法接受callback
函数作为参数。
The map() method creates a new array with the results of calling a provided function on every element in this array.
var array=obj.list.map(callback);
function callback(item){
return item.name;
}
或者简单地说:
var array=obj.list.map(el=>el.name);
var obj={
"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]
}]
};
console.log(obj.list.map(function(item){
return item.name;
}));
关于javascript - NodeJS - 从多级对象数组中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42426244/