Reputation: 88
How can I access each of the properties in the given JSON?
I would also like to filter the particular objects based on their IDs. How to do that using array.filter method in javascript?
{
"records": [
{
"id": "abcd",
"fields": {
"term": [
"xyz"
],
"groupId": 888,
"url": "https://www.facebook.com",
"url_c": [
"https://www.google.com"
],
"pID": [
"1800"
],
"location": [
"mumbai"
],
"url_location": [
"https://www.mumbai.com/"
]
},
"createdTime": "2021-05-12T10:18:33.000Z"
}
]
}
Currently I'm trying to do this:
const [info, setInfo] = useState({});
useEffect(() => {
fetch(
"https://apiurl//"
)
.then((res) => res.json())
.then((data) => {
setInfo(data.records);
console.log(data);
})
.catch((error) => {
console.log(error);
});
}, []);
let resultInfo = info.filter((x) => x.groupId == gid);
console.log(resultInfo[0].fields.groupId);
But it shows error
Upvotes: 0
Views: 57
Reputation: 236
Since it's asynchronous either define things in .then() method or you can simply use asyn await to let things work for you.
Something like
const [info, setInfo] = useState([]);
useEffect(() => {
fetch(
"https://apiurl//"
)
.then((res) => res.json())
.then((data) => {
if(data && data.records){
console.log(data);
const records = data.records.filter((x) => x.fields.groupId == gid);
setInfo(records);
// if you will log info here most probably it might log default value so check in your render method for the latest value
}
})
.catch((error) => {
console.log(error);
});
}, []);
Make sure gid is same as your groupId. For surity you can just pass static number just to test. Now try to access info in your render method like:
return
<div>
{JSON.stringify(info)}
</div>
Upvotes: 0
Reputation: 865
You're initializing your info
as an empty object. So your code is trying to run filter
on an object which will return an error. Also in your filter check is wrong based on the json example you shared
You should change
const [info, setInfo] = useState({});
let resultInfo = info.filter((x) => x.groupId == gid);
to
const [info, setInfo] = useState([]);
let resultInfo = info.filter((x) => x.fields.groupId == gid);
Upvotes: 1