Home > OS >  How to parse an array inside an object
How to parse an array inside an object

Time:10-06

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": [
            "[email protected]",
            "[email protected]",
            "[email protected]"
        ],
        "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;  
});

CodePudding user response:

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": [
            "[email protected]",
            "[email protected]",
            "[email protected]"
        ],
        "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)
})

CodePudding user response:

With modern javascript you also can do it this way:

for (const result of jsonString.results) {
  console.log(result.priority);
}

for..of loop documentation

CodePudding user response:

you should use .results property here

jsonString.results.forEach(result => {
  console.log(result.priority); // prints priority in console
});

if you need to have a priorities array you can use

let priorities = jsonString.results.map(result => {
  return result.priority;
});

  • Related