I’m having problems getting the nested car values using javascript (lodash). Here is the JSON.
{
"cars":[
{
"nestedCars":[
{
"car":"Truck",
"color":"Red",
"type":"Honda"
}
]
},
{
"nestedCars":[
{
"car":"Sedan",
"color":"Blue",
"type":"Ford"
}
]
},
]
}
The JSON response data is coming back fine.
this.carLevels = response.data.cars;
The below code giving me back all data an I’m expecting only 2 cars (Truck and Sedan).
carData() {
result = _.filter(this.carLevels, "nestedCars[0].car")
}
I also tried nested functions but get nothing.
result = this.carLevels.filter(function (a) {
return a.nestedCars.some(function (b) {
return b.car;
});
});
What am I doing wrong?
Basically I’m attempting to retrieve all car items from JSON.
Expected result:
car:"Truck"
car:"Sedan"
3
Answers
You could take
Array#flatMap
for the outer array and map thecar
property of the inner arrays.Firstly, the JSON sample provided won’t yield the expected results as it has inconsistent syntaxes. Here is a better sample below to get values from car[array]
With this, you can easily use the snippet below
flatMap
should do the trick:Basically, if you only want to "extract" things, you need
map
orflatMap
, notfilter
orsome
.