I just need to retrieve an object by its id from this JSON object (peopleData). When I do typeof peopleData
, it returns object. When I try to do typeof peopleData[0]
(treating this object as an array because it has brackets as the opening and closing elements) it returns undefined
. How do I loop through all of the objects to find the appropriate object if this JSON object is an array that returns "undefined" when I try to get a specific element of that array? I don't know how to enumerate over or de-structure this object since it is an array.
Here are the first few lines from the JSON that I was given (I changed the values but that is irrelevant. I am mainly emphasizing the bracket at the beginning). This is the raw JSON object that I copied from its raw form on GitHub:
[{
"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",
I have done this before with this exact data and it worked when I just used a small function that cycles through each element of the array, but I have no idea why it is not working now.
CodePudding user response:
You can use filter by the id you want.
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])
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I diagnosed my problem incorrectly. It did not have to do with the JSON data. I forgot to use await
when getting the data with Axios. Thanks so much for any effort you put in to help me with this.