I have a complex JS array of objects and properties. Some of them return value but some return null, the problem is when I am mapping through the list it causes error whenever there is a null value.
I cannot filter out the array right now because I am already inside a loop and should not create another filtered array. What would my best approach be? I want my loop to return Array.Group.name[0].text and if it is not there just return null.
const x = [
{
"id": "1",
"Groups": [
{
"name": [
{
"language": "en-US",
"text": "REGULAR_TIME"
}
],
"isSystem": true
},
{
"name": [
{
"language": "en-US",
"text": "CHARGEABLE"
}
],
"isSystem": true
}
]
},
{
"id": "2",
"Groups": [
{
"name": [
{
"language": "en-US",
"text": "REGULAR_TIME"
}
],
"isSystem": true
},
{
"name": [
{
"language": "en-US",
"text": "CHARGEABLE"
}
],
"isSystem": true
}
]
}
]
x.map(y=>y.Groups.name[0].text)
console.log(x)
CodePudding user response:
Groups
is an array too, so you have to use indexes to access its members like Groups[0]
. It is not clear the name of what Groups
element you want to get though.
Probably, you meant x.map(y=>y.Groups[0].name[0].text)
Groups
being an array is an object too. so Groups.name
gives you nothing since such a property isn't present.
let x = [
{
"id": "1",
"Groups": [
{
"isSystem": true
},
{
"name": [
{
"language": "en-US",
"text": "CHARGEABLE"
}
],
"isSystem": true
}
]
},
{
"id": "2",
"Groups": [
{
"name": [
{
"language": "en-US",
"text": "REGULAR_TIME"
}
],
"isSystem": true
},
{
"name": [
{
"language": "en-US",
"text": "CHARGEABLE"
}
],
"isSystem": true
}
]
}
];
console.log(x.map(y => y.Groups[0].name?.[0].text));
// or just filter the absent names out before the main routine.
console.log(x.filter(y => y.Groups[0].name).map(y => y.Groups[0].name?.[0].text));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
here is the problem !
Groups
is an array so :
let result = [];
for (i=0; i<x.length;i ){
for(j=0;j<x[i].Groups.length;j ){
result.push(x[i].Groups[j].name[0].text)
}
}
this loop returns a result that contains an array of text
or you can try this :
x.forEach(el=>{
el.Groups.forEach(v=>{
result.push(v.name[0].text)
})
})