如何在JavaScript中过滤和映射对象数组? [英] How to filter and map array of objects in JavaScript?
问题描述
我有一个对象数组,
我想从中有条件地创建另一个对象数组。
I have an array of objects,
From which I want to conditionally create another array of objects.
例如。 -
var devs = [
{
name: 'A',
age: 26,
tech: ['JavaScript','React'],
addr:{
country:'India',
city:'Pune'
}
},
{
name: 'B',
age: 25,
tech: ['Node','AngularJs'],
addr:{
country:'USA',
city:'NY'
}
},
{
name: 'C',
age: 27,
tech: ['React','AWS'],
addr:{
country:'UK',
city:'London'
}
}
]
我想要一个对象数组在其技术字段数组中具有反应 ,
只希望显示其名称和技术,
以下是预期输出-
I want an Array of objects who have 'React' in their 'tech' field array,
And only want to display their Name and Tech,
The following is the expected output -
[
{
name: 'A',
tech: ['JavaScript','React']
},
{
name: 'C',
tech: ['Java','React'],
}
]
我知道可以使用条件过滤器方法,
但是如何从对象数组中排除不必要的字段?
可以在此处使用map方法吗?如果是这样,我该如何实现呢?
I know for conditional purpose filter method can be used,
But how do I leave out the unnecessary fields from the array of objects?
Can map method be used here? If so how do I implement it?
以下是我的半熟代码-
var filteredDevs = devs.filter(temp => temp.tech.includes('React'));
推荐答案
您可以使用 Array.filter
和 Array.map
进行操作,使用 Array.includes
在其中检查 tech
数组中是否存在 React 。
You can use Array.filter
and Array.map
to do it, filter using the Array.includes
where you check for the presence of React in the tech
array.
第二个步骤是通过仅保留原始对象的 name
和 tech
属性来映射到所需对象。
Second step is to map to the desired object by retaining only name
and tech
properties from the original object.
const devs = [{"name":"A","age":26,"tech":["JavaScript","React"],"addr":{"country":"India","city":"Pune"}},{"name":"B","age":25,"tech":["Node","AngularJs"],"addr":{"country":"USA","city":"NY"}},{"name":"C","age":27,"tech":["Java","AWS"],"addr":{"country":"UK","city":"London"}}];
const devReact = devs.filter(obj => obj.tech.includes("React")).map(obj => ({"name":obj.name, "tech":obj.tech}));
console.log(devReact);
您也可以在使用 Array.reduce
You can also do it in one shot using Array.reduce
, where you accumulate only those objects having React in the array.
const devs = [{"name":"A","age":26,"tech":["JavaScript","React"],"addr":{"country":"India","city":"Pune"}},{"name":"B","age":25,"tech":["Node","AngularJs"],"addr":{"country":"USA","city":"NY"}},{"name":"C","age":27,"tech":["Java","AWS"],"addr":{"country":"UK","city":"London"}}];
const devReact = devs.reduce((acc, ele) => ele.tech.includes("React") ? acc.concat({"name": ele.name, "tech":ele.tech}): acc ,[]);
console.log(devReact);
这篇关于如何在JavaScript中过滤和映射对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!