简体   繁体   中英

How to find object inside array inside object

Pardon my confusion but how can I get the value of the name key nested inside this object:

{
    "id":"5SA72165CP580074WLPMNIYA",
    "transactions":[{
        "amount":{
            "total":"23.80",
        },
        "item_list":{
            "items":[{
                "name":"Gateway", // THIS!
            }]
        },
        "related_resources":[{
            "sale":{
                "id":"1PD13091HH4593923",
            }
        }]
    }]
}

I am trying to get it like this:

console.log(transactions[item_list.items[name]])

and it's returning undefined

May be something like this

let dynamicContent = {
    "id":"5SA72165CP580074WLPMNIYA",
    "transactions":[{
        "amount":{
            "total":"23.80",
        },
        "item_list":{
            "items":[{
                "name":"Gateway", // THIS!
            }]
        },
        "related_resources":[{
            "sale":{
                "id":"1PD13091HH4593923",
            }
        }]
    }]
};

dynamicContent.transactions.forEach(function(itemList) {
  itemList.item_list.items.forEach(function(element){
    if(element.hasOwnProperty("name")) {
      console.log(element["name"]);
    }
  });
});

I am basically iterating over the array part. You can play around with the above logic to get what you want.

Hope this helps!

如果您知道属性的索引不会更改,则可以按索引进行深入研究:

console.log(transactions[0].item_list.items[0].name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM