gpt4 book ai didi

javascript - 在 Object.keys(obj) 中只工作部分时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:19 25 4
gpt4 key购买 nike

我试图查看某个数字是否在 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",
}

最佳答案

您可以避免使用 for..in 来迭代数组。或者,您可以在 arrayOfNumbersIHave 上使用 reduce & 在每次迭代中,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)

关于javascript - 在 Object.keys(obj) 中只工作部分时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55476937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com