简体   繁体   English

如何在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. 我要从中有条件地创建另一个对象数组。

Eg. 例如。 - --

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'],
    }
]

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? 如果是这样,我该如何实施?

Following is my half cooked code - 以下是我半熟的代码-

var filteredDevs = devs.filter(temp => temp.tech.includes('React'));

You can use the filter + map functions, however that approach uses two loops for doing what you want. 您可以使用filter + map函数,但是该方法使用两个循环来完成所需的操作。

This alternative uses the function reduce to generate the desired output 此替代方法使用函数reduce生成所需的输出

 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' } }], result = devs.reduce((a, {name, tech}) => { if (tech.includes('React')) a.push({name, tech}); return a; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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. 您可以使用Array.filterArray.map使用做到这一点,过滤器Array.includes在您检查的在阵营的存在tech阵列。

Second step is to map to the desired object by retaining only name and tech properties from the original object. 第二步是通过仅保留原始对象的nametech属性来映射到所需对象。

 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); 


You can also do it in one shot using Array.reduce , where you accumulate only those objects having React in the array. 您也可以使用Array.reduce一次完成此操作,在此仅累积那些在数组中具有React的对象。

 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); 

I will better use Array.reduce() for this task, to loop only once over the input data. 我最好将Array.reduce()用于此任务,以在输入数据上仅循环一次。

 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'} } ]; let res = devs.reduce((acc, {name, tech}) => { tech.includes("React") && acc.push({name, tech}); return acc; }, []); console.log(res); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

You could filter and map the wanted properties. 您可以过滤和映射所需的属性。

 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' } }], result = devs .filter(({ tech }) => tech.includes('React')) .map(({ name, tech }) => ({ name, tech })); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can use Array.prototype.map() to remove unnecessary fields 您可以使用Array.prototype.map()删除不必要的字段

 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: ['Java','AWS'], addr:{ country:'UK', city:'London' } } ] let newArr =devs.filter(temp => temp.tech.includes('React')).map(({name,tech}) => ({name,tech})); console.log(newArr); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM