如何检索Java脚本对象名称数组

时间:2017-07-22 21:37:55

标签: javascript arrays json

我正在尝试检索汽车名称(即" Ford feigo"," Nissan"," Duster")。我正试图通过carsinfo["0"].name检索它们以获取汽车名称,但它会给我 undefined 作为回报。

var carsinfo =    {"cars": [
            {
                "Ford feigo": {
                    "milege": "11",
                    "color": "White",
                    "electric": yes
                }
            },
            {
                "Nissan": {
                    "milege": "33",
                    "color": "Black",
                    "electric": 74
                }
            },
            {
                "Duster": {
                   "milege": "26",
                    "color": "RED",
                    "electric": 87
                }
            }
        ],
    };

4 个答案:

答案 0 :(得分:0)

您可以使用Object.keysArray#map一起检索它们。

let carsinfo = {
  "cars": [{
      "Ford feigo": {
        "milege": "11",
        "color": "White",
        "electric": 'yes'
      }
    },
    {
      "Nissan": {
        "milege": "33",
        "color": "Black",
        "electric": 74
      }
    },
    {
      "Duster": {
        "milege": "26",
        "color": "RED",
        "electric": 87
      }
    }
  ],
};

let cars = [].concat(...carsinfo.cars.map(Object.keys));

console.log(cars);

答案 1 :(得分:0)

汽车名称是对象中的键,要获取它们,您可以映射周围的数组,然后在新数组中获取键名称,您可以根据索引访问每个键

var carsinfo = {
  "cars": [{
    "Ford feigo": {
      "milege": "11",
      "color": "White",
      "electric": "yes"
    }
  }, {
    "Nissan": {
      "milege": "33",
      "color": "Black",
      "electric": 74
    }
  }, {
    "Duster": {
      "milege": "26",
      "color": "RED",
      "electric": 87
    }
  }],
};

var names = carsinfo.cars.map( k => Object.keys(k).shift());

console.log(names[0])

答案 2 :(得分:0)

您可以使用Array#reduce的经典方法:



var carsinfo = { cars: [{ "Ford feigo": { milege: "11", color: "White", electric: true } }, { Nissan: { milege: "33", color: "Black", electric: 74 } }, { Duster: { milege: "26", color: "RED", electric: 87 } }] },
    cars = carsinfo.cars.reduce((r, o) => r.concat(Object.keys(o)), []);

console.log(cars);




答案 3 :(得分:0)

对象carsinfo没有名为^Csignal: 2 signal: 2 signal: 2 killing child: 14109 killing child: 14110 killing parent: 14104 suicide: 14108 Killed 的密钥。这就是你获得name的原因。您需要重新构建阵列并执行以下操作:

undefined

这不是一个好的解决方案,因为它仅对这个特定的用例有效。