gpt4 book ai didi

javascript - 如果 JSON 和 Array 中存在相同的值,请执行某些操作

转载 作者:行者123 更新时间:2023-11-28 13:00:34 24 4
gpt4 key购买 nike

我对逻辑有一个粗略的了解,但如果有人可以提供帮助,非常感谢!

尝试查看 JSON(来自 URL)和数组中是否有任何数字匹配。如果确实如此,那就做点什么吧。在此示例中,300 是 JSON 和数组中都存在的数字。

可能的逻辑/代码

// FOR json
for(var i = 0; i < obj.length; i++) {
var myObjNum = obj[i];
}

// FOR myArray
for(var i = 0; i < myArray.length; i++) {
var myArrayNum = myArray[i];
}

// if cat ID is in the DOM and array, do something
if (myObjNum == myArrayNum) {
// if a number is found in both the array and JSON, do something here
}

JSON (https://api.myjson.com/bins/svr3i)

[
{

"5774": {
"subCats": [
{
"town": "atlanta",
"state": "georgia"
}
]
},
"300": {
"subCats": [
{
"town": "new york city",
"state": "new york"
}
]
},
"899": {
"subCats": [
{
"town": "san diego",
"state": "california"
}
]
},
"2557": {
"subCats": [
{
"town": "chicago",
"state": "illinois"
}
]
}

}
]

数组

var myArray = [500,4743,300,77899];

最佳答案

只需使用嵌套循环

var JSON = [
{

"5774": {
"subCats": [
{
"town": "atlanta",
"state": "georgia"
}
]
},
"300": {
"subCats": [
{
"town": "new york city",
"state": "new york"
}
]
},
"899": {
"subCats": [
{
"town": "san diego",
"state": "california"
}
]
},
"2557": {
"subCats": [
{
"town": "chicago",
"state": "illinois"
}
]
}

}
]


var myArray = [500,4743,300,77899];

Object.keys(JSON[0]).forEach(key => {
myArray.forEach(item => {
if(item == key){
// do something here
console.log('action');
}
});
});

关于javascript - 如果 JSON 和 Array 中存在相同的值,请执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50991422/

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