skip to Main Content

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


  1. You could take Array#flatMap for the outer array and map the car property of the inner arrays.

    const
        data = { cars: [{ nestedCars: [{ car: "Truck", color: "Red", type: "Honda" }] }, { nestedCars: [{ car: "Sedan", color: "Blue", type: "Ford" }] }] },
        cars = data.cars.flatMap(({ nestedCars }) => nestedCars.map(({ car }) => car));
    
    console.log(cars);
    Login or Signup to reply.
  2. 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]

      {
      "cars": [
        {
          "car": "Truck",
          "color": "Red",
          "type": "Honda"
        },
        {
          "car": "Sedan",
          "color": "Blue",
          "type": "Ford"
        }
      ]
    }
    

    With this, you can easily use the snippet below

        data.cars.forEach(function(car) {
      console.log("Car: " + car.car);
      console.log("Color: " + car.color);
      console.log("Type: " + car.type);
    });
    
    Login or Signup to reply.
  3. flatMap should do the trick:

    let allCars = response.data.cars.flatMap(
        car => car.nestedCars.map(
            item => item.car))
    

    Basically, if you only want to "extract" things, you need map or flatMap, not filter or some.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search