过滤一组对象并使用一组键提取其属性

时间:2017-06-20 16:32:25

标签: javascript arrays object dictionary filter

我有这个问题,我无法绕过我的脑袋,

如果放入代码,

会好得多。

//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'];

我一直在使用过滤器和地图但没有用,还尝试在地图中嵌套过滤器获取数组数组,内部是单个对象。

4 个答案:

答案 0 :(得分:2)

您可以映射对象并重新映射所需的键以获取名称。



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




答案 1 :(得分:0)

我假设您需要将数组编号映射到id属性?这是代码,您在数组中map通过数字和find来处理对象数组中没有此类id的情况:

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)

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我认为你使用过滤器走在了正确的轨道上。您可以使其可读性和简洁性。

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

更短的东西!会是

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