如何使用Javascript访问2个数组中的嵌套对象

问题描述 投票:0回答:2

我在使用 javascript (lodash) 获取嵌套汽车值时遇到问题。这是 JSON。

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

   ]
 }

JSON 响应数据正常返回。

 this.carLevels = response.data.cars;

下面的代码给我返回所有数据,我预计只有 2 辆车(卡车和轿车)。

 carData() {   
   result = _.filter(this.carLevels, "nestedCars[0].car")
       }

我也尝试过嵌套函数,但什么也没得到。

  result = this.carLevels.filter(function (a) {
    return a.nestedCars.some(function (b) {
        return b.car;
     });
  });

我做错了什么?

基本上我正在尝试从 JSON 检索所有汽车项目。

预期结果:
汽车:“卡车” 汽车:“轿车”

javascript arrays json lodash
2个回答
0
投票

您可以将

Array#flatMap
作为外部数组,并映射内部数组的
car
属性。

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);


0
投票

首先,提供的 JSON 示例不会产生预期结果,因为它的语法不一致。下面是一个更好的示例,用于从 car[array] 获取值

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

有了这个,您可以轻松使用下面的代码片段

    data.cars.forEach(function(car) {
  console.log("Car: " + car.car);
  console.log("Color: " + car.color);
  console.log("Type: " + car.type);
});
© www.soinside.com 2019 - 2024. All rights reserved.