Object.keys(obj)中的内容仅能兼职工作

时间:2019-04-02 14:11:36

标签: javascript

由于某种原因,我试图查看一个数字是否在Object.keys()中,我得到了部分响应,某些数字未包含在最终对象中。知道为什么in只能在这里部分工作吗?

var arrayOfNumbersIHave = [
  "542009988",
  "7411111111",
  "542261111",
  "542009988",
  "7411111111",
  "7411111111",
  "7442334675",
  "661766029",
  "692549335",
]

var snapObject = {
  "542009988": "A",
  "542261111": "B",
  "661766029": "C",
  "6617666029": "D",
  "692549335": "E",
  "7442334675": "F",
  "7411111111": "G",
}

var objToDisplay = {};

for (const i in arrayOfNumbersIHave) {
  if (i in Object.keys(snapObject)) {
    objToDisplay[arrayOfNumbersIHave[i]] = snapObject[arrayOfNumbersIHave[i]]

  }
}

console.log(objToDisplay)

结果:

{
  "542009988": "A",
  "542261111": "B",
  "7442334675": "F",
  "7411111111": "G",
}

预期结果:

{
  "542009988": "A",
  "542261111": "B",
  "661766029": "C",
  "692549335": "E",
  "7442334675": "F",
  "7411111111": "G",
}

4 个答案:

答案 0 :(得分:4)

以这种方式使用in operator不太正确。 in检查对象中的属性或数组中的 索引 。因此,仅当您要检查的数字恰好是数组中的索引时,它才可能返回true

因此,在这种情况下,您真的想省略Object.keys,而是使用:

for (const i in arrayOfNumbersIHave) {
  if (arrayOfNumbersIHave[i] in snapObject) {
    objToDisplay[arrayOfNumbersIHave[i]] = snapObject[arrayOfNumbersIHave[i]]
  }
}

正如@adiga在下面指出的那样,我们可以使用for...of循环来简化此过程,以得到:

for (const val of arrayOfNumbersIHave) {
  if (val in snapObject) {
    objToDisplay[val] = snapObject[val];
  }
}

答案 1 :(得分:4)

您可以避免使用for..in来迭代数组。或者,您可以在reduce上使用arrayOfNumbersIHave,在每次迭代中,curr参数将代表arrayOfNumbersIHave的每个元素。使用此curr检查snapObject中是否存在同名密钥。是这样,然后在累加器对象中添加键和值

let arrayOfNumbersIHave = [
  "542009988",
  "7411111111",
  "542261111",
  "542009988",
  "7411111111",
  "7411111111",
  "7442334675",
  "661766029",
  "692549335",
]

let snapObject = {
  "542009988": "A",
  "542261111": "B",
  "661766029": "C",
  "6617666029": "D",
  "692549335": "E",
  "7442334675": "F",
  "7411111111": "G",
}

let objToDisplay = arrayOfNumbersIHave.reduce(function(acc, curr) {
  if (snapObject[curr]) {
    acc[curr] = snapObject[curr]
  }
  return acc;
}, {}) // {} is accumulator object 

console.log(objToDisplay)

答案 2 :(得分:4)

您需要检查数组的值(如果它在对象中),而不是通过获取索引来检查索引是否在数组中。

此行

if (arrayOfNumbersIHave[i] in snapObject) {

arrayOfNumbersIHave[i]的值用作用于与in operator和一个对象进行检查的键。

var arrayOfNumbersIHave = ["542009988", "7411111111", "542261111", "542009988", "7411111111", "7411111111", "7442334675", "661766029", "692549335"],
    snapObject = { 542009988: "A", 542261111: "B", 661766029: "C", 6617666029: "D", 692549335: "E", 7442334675: "F", 7411111111: "G" },
    objToDisplay = {};

for (const i in arrayOfNumbersIHave) {
    if (arrayOfNumbersIHave[i] in snapObject) {
        objToDisplay[arrayOfNumbersIHave[i]] = snapObject[arrayOfNumbersIHave[i]];
    }
}

console.log(objToDisplay);

答案 3 :(得分:0)

您可以简单地在第一个数组上进行迭代,并检查当前项在snapObject中是否存在,如果是,只需在objToDisplay中创建一个条目(键)并分配匹配的值即可:

arrayOfNumbersIHave.forEach(function(number) {
  if (snapObject[number]) objToDisplay[number] = snapObject[number];
});