So I have this originalArray:
[
[
{
“name”: “Selena”,
“lastName”: “Gomez”,
“likes”: {
“color”: “red”,
“country”: “Argentina”,
“state”: {
“name”: “Buenos Aires”
}
},
“phoneNumber”: “5555555555”,
“isAvailable”: false
}
],
[
{
“name”: “Nick”,
“lastName”: “Jonnas”,
“likes”: {
“color”: “blue”,
“country”: “Argentina”,
“state”: {
“name”: “Buenos Aires”
}
},
“phoneNumber”: “7777777777”,
“isAvailable”: true
},
{
“name”: “Joe”,
“lastName”: “Jonnas”,
“likes”: {
“color”: “yellow”,
“country”: “Argentina”,
“state”: {
“name”: “Buenos Aires”
}
},
“phoneNumber”: “9999999999”,
“isAvailable”: false
}
]
]
As you can see is an Object that has the form of (2) [Array(1), Array(2)] and I want to iterate over the object and get only the phoneNumbers items.
Expected output:
['55555555555', '7777777777', '9999999999']
I've tried:
const newArray= originalArray.map(element => element.phoneNumber);
But it returns undefined, actually I tried accessing with . like originalArray.phoneNumber and shows undefined too.
I also tried with this approach with no result:
var newArray = originalArray.filter(obj => {
return obj.phoneNumber != null
})
Is there a way to iterate over the object, look up the phoneNumber key, and add those results to a new array?
originalArrayis an Array of Arrays. Arrays do not have aphoneNumberproperty. I don’t know why you expected thisfilterto work. Arrays don’t have avalueproperty either; none of your objects do. Have you considered flattening the array first?typeof(originalArray)it returns'object'?