筛选对象数组并通过使用一组键来提取其属性 [英] Filter an array of objects and extract its property by using an array of keys
本文介绍了筛选对象数组并通过使用一组键来提取其属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果放在一个代码里面,这个问题我不能包住我的脑袋。
//对象数组样本
var objects = [{id:1,name:'test1'},{id:2,name:'test2'}, {id:3,name:'test3'},{id:4,name:'test4'}];
var arrayOfKeys = [3,1,4];
//如果它的id属性相当于arrayOfKeys [3,1]
// var arrayOfKeys = [3,1,4];
//输出示例:extractedName = ['test3','test1','test4'];
我已经使用过滤器和映射但没有用,数组和内部的数组是单个对象。
。$ b
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);
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);
这篇关于筛选对象数组并通过使用一组键来提取其属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文