Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting from json multidimensional array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading