I'm currently working on compiling a list from an array, but I've encountered an issue where some of the fields are null, causing the code to break and return:
obj.names is null
Below is the snippet of code that's causing the problem:
My Code
var data = {
"people": [{
"id": "32",
"description": "some description",
"archived": "",
"new": 0,
"names": [{
"name": "name 1",
"translations": null
}, {
"name": "name 2",
"translations": null
}],
}, {
"id": "56",
"description": "some description",
"archived": "",
"new": 0,
"names": [{
"name": "name 3",
"translations": null
}, {
"name": "name 4",
"translations": null
}],
}, {
"id": "99",
"description": "some description",
"archived": "",
"new": 0,
"names": null,
},
]
};
var mainData = [data];
var namesList = [];
for (var i = 0; i < mainData[0].people.length; i++) {
var obj = mainData[0].people[i];
if(obj.names) {
var nme = obj.names.name;
namesList.push(nme);
}
}
console.log(namesList); //This should have the list of names
<div id="container"></div>
How can this issue be resolved?