首页 > 解决方案 > How to parse an array inside an object

问题描述

Here is my array which I need to parse, as I am parsing array it is showing me undefined in console.

var jsonString = {
    "results": [{
        "cc_emails": [
            "test@test.com",
            "test1@test.com",
            "tst2@tst2.com"
        ],
        "name": "test",
        "email": "testemail",
        "email_config_id": 14000037621,
        "priority": 2,
        "product_id": null,
        "created_at": "2021-10-05T22:01:17Z",
        "updated_at": "2021-10-05T22:05:05Z"

    }]
}

I need to correct the above error and show priority. Here is my code which consists of forEach() loop with which I was iterating the array.

// I used foreach here.
$.each(jsonString, function (index, val) 
{
    alert jsonString[index].priority;  
});

标签: javascriptarraysobject

解决方案


your jsonString is an object that contains an array results. You need to apply forEach on the result instead of the object.

var jsonString = {
    "results": [{
        "cc_emails": [
            "test@test.com",
            "test1@test.com",
            "tst2@tst2.com"
        ],
        "name": "test",
        "email": "testemail",
        "email_config_id": 14000037621,
        "priority": 2,
        "product_id": null,
        "created_at": "2021-10-05T22:01:17Z",
        "updated_at": "2021-10-05T22:05:05Z"

    }]
}

jsonString.results.forEach(item => {
    console.log(item.priority)
})


推荐阅读