在id中键入的json过滤并返回一个数组;没有未定义的地图

时间:2017-01-22 18:08:42

标签: javascript json filter key

我有

let list = { 
  1: { name: "someone1" },
  5: { name: "someone5" },
  7: { name: "someone7" },
  8: { name: "someone8" }
};

我想过滤[1,5,42]

[
 { name: "someone1" },
 { name: "someone5" }
]

我试过

Object.keys(list).map(key=> {if([1,5,42].includes(key)) return list[key]});

[
 { name: "someone1" },
 { name: "someone5"},
 undefined, 
 undefined
]

PS:当我的列表是json数组时,我使用了list.filter(person => [1,5].includes(person.id))。然后我改为使用id模型键入,所以我可以使用liat[id],这比list.filter对单个元素更快。

4 个答案:

答案 0 :(得分:3)

您可以直接迭代过滤器数组并获取对象。



let list = { 1: { name: "someone1" }, 5: { name: "someone5" }, 7: { name: "someone7" }, 8: { name: "someone8" } },
    filter = [1, 5],
    result = filter.map(k => list[k]);

console.log(result);




如果过滤器包含不是对象键的字符串,则需要采用不同的方法。



let list = { 1: { name: "someone1" }, 5: { name: "someone5" }, 7: { name: "someone7" }, 8: { name: "someone8" } },
    filter = [1, 5, 42],
    result = filter.reduce((r, k) => r.concat(list[k] || []), []);

console.log(result);




一个两步解决方案,用于映射对象的值,并使用Boolean过滤真实元素。



let list = { 1: { name: "someone1" }, 5: { name: "someone5" }, 7: { name: "someone7" }, 8: { name: "someone8" } },
    filter = [1, 5, 42],
    result = filter.map(key => list[key]).filter(Boolean);

console.log(result);




答案 1 :(得分:1)

您可以使用解构分配

let res = [];
({1:res[res.length], 5:res[res.length]} = list);

let list = { 
  1: { name: "someone1" },
  5: { name: "someone5" },
  7: { name: "someone7" },
  8: { name: "someone8" }
};

let [keys, res] = [["1", "5"], []];

for (let key of keys) {({[key]:res[res.length]} = list)}

console.log(res);

答案 2 :(得分:0)

let list = { 
  1: { name: "someone1" },
  5: { name: "someone5" },
  7: { name: "someone7" },
  8: { name: "someone8" }
};
function filter(ids, list){
  var ret = [];
  for(var i in ids){
    var id = ids[i];
    ret.push(list[id]);
  }
  return ret;
}
var filtered = filter([1,5], list);
console.log(filtered);

此解决方案假设您只询问现有密钥。

答案 3 :(得分:0)

单线解决方案

[1,5,42].map(key => list[key]).filter(el => el)
// if(el != null) return true shortened as el => el

Nina Scholz的简单单行:[1,5,42].reduce((r, k) => r.concat(list[k] || []), []);不同之处在于它在将数据添加到数组之前进行检查,而上面的数据在构建数组后删除了undefined

还有一个可能的单行

["1","5","42"].filter(key => Object.keys(list).includes(key)).map(key => list[key])
//This one removes the invalid keys and then build an array without `undefined`s

<强>段

let list = { 
  1: { name: "someone1" },
  5: { name: "someone5" },
  7: { name: "someone7" },
  8: { name: "someone8" }
};

console.log([1,5,42].map(key => list[key]).filter(el => el));

console.log(["1","5","42"].filter(key => Object.keys(list).includes(key)).map(key => list[key]));