Javascript NodeJS-从多层次对象数组中提取数据
我有以下JSON数组:Javascript NodeJS-从多层次对象数组中提取数据,javascript,arrays,node.js,object,Javascript,Arrays,Node.js,Object,我有以下JSON数组: { "list": [{ "name": "Assignment", "id": 67, "template": 0, "children": [{ "assignmentnumber": 1000, "fromCountry": "Sweden", "toCountry": "Spain", "fromCity": "Stockholm", "toCity":
{
"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
方法,该方法接受回调函数作为参数
map()方法使用调用
在此数组中的每个元素上提供函数
或者简单地说:
var array=obj.list.map(el=>el.name);
var obj={
“名单”:[{
“名称”:“分配”,
“id”:67,
“模板”:0,
“儿童”:[{
“转让编号”:1000,
“fromCountry”:“瑞典”,
“toCountry”:“西班牙”,
“fromCity”:“斯德哥尔摩”,
“toCity”:“马德里”
}, {
“转让编号”:15678,
“fromCountry”:“瑞典”,
“toCountry”:“德国”,
“fromCity”:“斯德哥尔摩”,
“toCity”:“柏林”
}, {
“转让编号”:10001,
“fromCountry”:“瑞典”,
“toCountry”:“联合王国”,
“fromCity”:“斯德哥尔摩”,
“toCity”:“伦敦”
}]
}, {
“名称”:“估价表”,
“id”:36,
“模板”:0,
“儿童”:[15678]
}, {
“名称”:“索赔”,
“id”:12,
“模板”:0,
“儿童”:[100010001]
}]
};
console.log(obj.list.map)(功能(项){
返回item.name;
}));代码>您可以使用本机阵列API在不使用lodash的情况下执行此操作
const obj = { /* The JSON in your question */ };
const names = obj.list.map(item => item.name);
Array.map()
接受一个函数并对数组中的每个项调用该函数,返回一个包含每个项结果的新数组。map是最好的方法,正如其他人所说的那样。另一种选择是使用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
}
@JPlexor,它对你有用吗?它就像一个符咒;-)谢谢大家!!
var children = obj.children;
var array_of_names;
children.forEach(function (item)){
array_of_names.push(item.name);
//... Do more operations for each item
}