查找对象键是否在数组javascript中

时间:2019-05-14 09:18:22

标签: javascript arrays object

所以我有一个ID数组,请考虑以下内容

let ids = [1,2,3]

然后是一个对象,请考虑以下内容

let obj = {1:true, 2:true, 100:true}

我该如何找到对象键是否在数组中,因为结构很奇怪,所以它通常不带有类似的东西

let obj = { id: 1, value:true}

它只是将键作为ID,将值作为键值的右侧

3 个答案:

答案 0 :(得分:1)

全部找到id并与对象进行映射。

let ids = [1, 2, 3],
    obj = { 1: true, 2: true, 100: true },
    result = ids
        .filter(k => k in obj)
        .map(id => ({ id, value: obj[id] }));

console.log(result);

第一个发现的结果

let ids = [1, 2, 3],
    obj = { 1: true, 2: true, 100: true },
    result = (id => ({ id, value: obj[id] }))(ids.find(k => k in obj));

console.log(result);

答案 1 :(得分:0)

let ids = [1,2,3]

let obj = {1:true, 2:true, 100:true}

// test if the object has at least one key that is listed in [ids]
console.log(Object.keys(obj).some(x => ids.includes(Number(x)))); // true

// get the object keys that exist in [ids] and convert them to numbers
console.log(Object.keys(obj).filter(x => ids.includes(Number(x))).map(x=>Number(x))); // [1,2]

答案 2 :(得分:0)

let ids = [1,2,3];
let obj = {1:true, 2:true, 100:true};

let result = Object.keys(obj).filter(id => {
    if(ids.indexOf(Number(id))>-1){return true}
})

结果是具有匹配ID的数组。