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

How to retrieve JSON value based on the value of a sibling element

Given the following JSON snippet

{
    "count": 4,
    "checks": 
    [   {
            "id": "8299393",
            "name": "NEW_CUSTOMER",
            "statusCode": "495"
        },

        {
            "id": "4949449",
            "name": "EXISTING_CUSTOMER",
            "statusCode": "497"
        }
       //Further values here
    ]
}

…how can I used Javascript to retrieve the id value 4949449 when I need to be sure it corresponds to the "name":"EXISTING_CUSTOMER" k/v pair as they are not ordered so I cannot use res.id[0] ?

//retrieve data via api call and read response into a const
const res = await response.json();

//get the id value 4949449 which corresponds to the sibling name whos value is 'EXISTING_CUSTOMER'   
const existingCustId = res.checks.name["EXISTING_CUSTOMER"].id; //doesn't work

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

>Solution :

If there would be only 1 EXISTING_CUSTOMER, you can use Array.find()

const data = {
    "count": 4,
    "checks": 
    [   {
            "id": "8299393",
            "name": "NEW_CUSTOMER",
            "statusCode": "495"
        },

        {
            "id": "4949449",
            "name": "EXISTING_CUSTOMER",
            "statusCode": "497"
        }
       //Further values here
    ]
}

const existingUserID = data.checks.find(i => i.name === "EXISTING_CUSTOMER").id

console.log(existingUserID)

If more than 1, you can use Array.filter() to get the customers:

const data = {
    "count": 4,
    "checks": 
    [   {
            "id": "8299393",
            "name": "NEW_CUSTOMER",
            "statusCode": "495"
        },

        {
            "id": "4949449",
            "name": "EXISTING_CUSTOMER",
            "statusCode": "497"
        },
        {
            "id": "5656565656",
            "name": "EXISTING_CUSTOMER",
            "statusCode": "497"
        }
       //Further values here
    ]
}

const existingUsers = data.checks.filter(i => i.name === "EXISTING_CUSTOMER")

console.log(existingUsers.map(i => i.id))
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