I have an array and trying to extract an object with an if statement that if a key equals a specific value then get that corresponding object. So what I’m trying to do is build an if statement that says, if "LABEL" equals "TitleOne" then output the ID and ADDRESS1
My json:
var data = [
[
{
"LABEL": "TitleOne"
},
{
"ID": "204",
"Address1": "123 main st",
}
],
[
{
"LABEL": "TitleTwo"
},
{
"Total": "17490"
"DaysDisplay": "5.0 days"
}
]
];
What I’m looking for is something like:
if(data[0].LABEL == 'TitleOne'){
console.log(data.[0].ID);
}
>Solution :
You can use filter()
to find the child arrays in your outer array which have the specified LABEL
. From there you can access the ID
and Address1
property values.
Note that the below code assumes only 1 LABEL
match per set. If you have more than one match you would need to loop through to retrieve the properties from each child array instead of accessing the 0th element.
const data = [
[{ "LABEL": "TitleOne" }, { "ID": "204", "Address1": "123 main st" }],
[{ "LABEL": "TitleTwo" }, { "Total": "17490", "DaysDisplay": "5.0 days" }]
];
let targetItem = data.filter(x => x[0].LABEL == 'TitleOne');
console.log(targetItem[0][1].ID)
console.log(targetItem[0][1].Address1)