Home > Software design >  How to retrieve JSON value based on the value of a sibling element
How to retrieve JSON value based on the value of a sibling element

Time:11-18

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

CodePudding user response:

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))

CodePudding user response:

I guess I typed too slowly. Harun beat me to it. :D

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

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


console.log(obj.checks.find(e=>e.name=="EXISTING_CUSTOMER").id)

  • Related