Please tell me. There is an Api request and in response I receive an array of the form:
{
"status": true,
"rspa": [
{
"address": "FB2A23D4-554E9",
"def": false,
"tk": false
},
{
"address": "FA0EBFB496DA-C5465A8D",
"def": true,
"tk": false
},
{
"address": "FA0434B496DA-C5465A8D",
"def": true,
"tk": false
}
]
}
How to loop through a list of addresses (address object) where the object is "def": true?
myArray = data.rspa
var addrs = myArray.map(function(elem){
return elem.address;
}).join(",");
console.log(addrs);
It works but displays all addresses. Result FB2A23D4-554E9,FA0EBFB496DA-C5465A8D,FA0434B496DA-C5465A8D
myArray = data.data.rspa
var idToLookFor = 'true';
var foundObject = myArray.filter(function(item) {
return item.def === idToLookFor;
})[0].address;
console.log(foundObject.address);
});
Gives an error message: Uncaught TypeError: Cannot read properties of undefined (reading ‘address’)
3
Answers
filter
andmap
do two different things, and what you want is a combination of both. When you usedmap
it "worked", except the results weren’t filtered. Justfilter
them first, thenmap
them into the structure you want. Thenjoin
and output the result.(Additionally, you want to use
true
instead of'true'
as the value to filter on, otherwise comparing with===
won’t return anything.)As an aside… You don’t even need
idToLookFor
in this case. Ifresult.def
istrue
then you can just return that value from thefilter
callback.simply use Array.prototype.reduce() method…
You have an error because you don’t handle the case where def is false