我有一个对象的JSON数组,格式为
var employees =
[
{
"employee1": "employee1",
"Details": [
{
"title": "Software Engineer",
"EmployeeId": 451
}
]
},
{
"employee2": "employee2",
"Details": []
},
{
"employee3": "employee3",
"Details": [
{
"title": "Test analyst",
"EmployeeId": 453
}
]
},
{
"employee4": "employee4",
"Details": [
{
"title": "Software engineer",
"EmployeeId": 487
},
{
"title": "Architect",
"EmployeeId": 500
}
]
}
]
获取EmployeeId的最佳方法是什么?
预期输出:
[451,453,487,500]
使用时:
console.log(Object.assign({}, ...employees).Details.map(t=>t.EmployeeId))
它将返回结果为:
[487,500]
是否可以将结果中的其他员工ID串联起来?
答案 0 :(得分:4)
首先-它不是JSON,而只是一个数组。其次,像这样使用flatMap
和map
:
var employees = [{
"employee1": "employee1",
"Details": [{
"title": "Software Engineer",
"EmployeeId": 451
}]
},
{
"employee2": "employee2",
"Details": []
},
{
"employee3": "employee3",
"Details": [{
"title": "Test analyst",
"EmployeeId": 453
}]
},
{
"employee4": "employee4",
"Details": [{
"title": "Software engineer",
"EmployeeId": 487
},
{
"title": "Architect",
"EmployeeId": 500
}
]
}
];
var ids = employees.flatMap(({ Details }) => Details.map(({ EmployeeId }) => EmployeeId));
console.log(ids);
没有flatMap
的预填充-由MDN's alternative提供:
var employees = [{
"employee1": "employee1",
"Details": [{
"title": "Software Engineer",
"EmployeeId": 451
}]
},
{
"employee2": "employee2",
"Details": []
},
{
"employee3": "employee3",
"Details": [{
"title": "Test analyst",
"EmployeeId": 453
}]
},
{
"employee4": "employee4",
"Details": [{
"title": "Software engineer",
"EmployeeId": 487
},
{
"title": "Architect",
"EmployeeId": 500
}
]
}
];
var ids = employees.reduce((acc, { Details }) => acc.concat(Details.map(({ EmployeeId }) => EmployeeId)), []);
console.log(ids);
答案 1 :(得分:0)
不是使用flatMap
来支持问题(尽管我认为这是一个很好的答案,请注意),这是一个依靠reduce
和spread operator
的答案:
employees
.reduce((a, v) =>
( v.Details && a.push(...v.Details.map(o=>o.EmployeeId)), a)
, []);
不使用spread
的{{1}}
flat
在没有employees
.reduce((a, v) =>
( v.Details && a.push(v.Details.map(o=>o.EmployeeId)), a.flat(1))
, []);
或spread
的情况下,利用flat
[].concat.apply([], arr)
这些工作示例:
employees
.reduce((a, v) =>
( v.Details && a.push(v.Details.map(o=>o.EmployeeId)), [].concat.apply([], a))
, []);
答案 2 :(得分:0)
您可以尝试嵌套的reduce
方法。这样可以快速运行,并且不需要使用任何ES5或更高版本。
var employees = [{
"employee1": "employee1",
"Details": [{
"title": "Software Engineer",
"EmployeeId": 451
}]
},
{
"employee2": "employee2",
"Details": []
},
{
"employee3": "employee3",
"Details": [{
"title": "Test analyst",
"EmployeeId": 453
}]
},
{
"employee4": "employee4",
"Details": [{
"title": "Software engineer",
"EmployeeId": 487
},
{
"title": "Architect",
"EmployeeId": 500
}
]
}
];
var ids = employees.reduce(function(a, b) {
return b.Details.reduce(function(c, d) {
c.push(d.EmployeeId);
return c;
}, a);
}, []);
console.log(ids);