我只需要从这个JSON对象(peopleData)中检索一个对象的id。当我做typeof peopleData
时,它返回object。当我尝试做typeof peopleData[0]
(把这个对象作为一个数组,因为它有括号作为开始和结束元素),它返回undefined
。如果JSON对象是一个返回"未定义"的数组,如何循环遍历所有对象以找到合适的对象?当我试图得到数组的一个特定元素时?我不知道如何枚举或解构这个对象,因为它是一个数组。
以下是我收到的JSON中的前几行(我更改了值,但这无关紧要)。我主要强调开头的括号)。这是我从GitHub上的原始形式复制的原始JSON对象:
[{
"id": "237856238235",
"ip_address": "3423423.42.42.4",
"ssn": "123133231",
"date_of_birth": "3123123",
"address": {
"home": {
"street_number": "231231",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef"
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
}, {
"id": "fwefewf",
"ip_address": "fwefwf",
"ssn": "wfwef",
"date_of_birth": "wefwef",
"address": {
"home": {
"street_number": "efwef",
我以前用这个确切的数据做过这个,当我只是使用一个小函数循环遍历数组的每个元素时,它工作了,但我不知道为什么它现在不工作。
我诊断错了。它与JSON数据无关。当使用Axios获取数据时,我忘记使用await
。非常感谢你为帮我做这件事所付出的努力。
您可以根据您想要的id使用过滤器。
const data = [{
"id": "237856238235",
"ip_address": "3423423.42.42.4",
"ssn": "123133231",
"date_of_birth": "3123123",
"address": {
"home": {
"street_number": "231231",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef",
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
},
{
"id": "fwefewf",
"ip_address": "fwefwf",
"ssn": "wfwef",
"date_of_birth": "wefwef",
"address": {
"home": {
"street_number": "efwef",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef",
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
}]
let result = data.filter(obj => obj.id === "237856238235")
//console.log(result)
console.log(result[0])