Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  149] [ 1]  / answers: 1 / hits: 31628  / 5 Years ago, sat, march 2, 2019, 12:00:00

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

More From » arrays

 Answers
5

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.



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








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




[#52496] Wednesday, February 27, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;