简体   繁体   中英

Filter an array of objects and extract its property by using an array of keys

im having this problem which i cant wrap around my head,

much better if put in a code.

//Array of objects sample
var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}];
var arrayOfKeys = [3,1,4];

//extract object name property if its id property is equivalent to one of arrayOfKeys [3,1] 
//var arrayOfKeys = [3,1,4];
//output sample: extractedName=['test3','test1','test4'];

i've been using filter and map but no avail, also tried nesting filter inside map im getting an arrays of array and inside is a single object.

You could map the objects and ren map the wanted keys for getting the name.

 var objects = [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }], arrayOfKeys = [3, 1], result = arrayOfKeys.map((map => id => map.get(id).name)(new Map(objects.map(o => [o.id, o])))); console.log(result); 

I assume you need to map array numbers to id properties? Here's the code where you map through numbers and find inside your array to handle situations when there's no such id in objects array:

 var objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}]; var arrayOfKeys = [3,1]; var res = arrayOfKeys.map(key => { var found = objects.find(o => o.id == key); return found ? found.name : false; }) console.log(res) 

 let objects = [{id:1, name:'test1'}, {id:2, name:'test2'}, {id:3, name: 'test3'}, {id:4, name:'test4'}], arrayOfKeys = [3,1,4]; let result = objects.reduce((res, obj) => { // loop over the array of objects let index = arrayOfKeys.indexOf(obj.id); // check if the current object's id is in the array of keys if(index !== -1) { // if it's there res.push(obj.name); // then add the current object's name to the result array arrayOfKeys.splice(index, 1); // remove its id from the array of keys so we won't search for it again (optional, slightly better than leaving it there) } return res; }, []); console.log(result); 

I think you were on the right track with the filter. You can make it readable and concise with some.

 var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}], arrayOfKeys = [3, 1, 4]; var result = objects.filter((x, i) => { if (arrayOfKeys.some(k => x.id === k)) { return true; } }) console.log(result.map(x=>x.name)); 

Something even shorter! would be

 var objects = [{id: 1,name: 'test1'}, {id: 2,name: 'test2'}, {id: 3,name: 'test3'}, {id: 4,name: 'test4'}],arrayOfKeys = [3, 1, 4]; var result = objects.filter((x, i) => arrayOfKeys.some(k => x.id === k)); console.log(result.map(x=>x.name)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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