如何获得所有产品的名称?

时间:2018-04-29 16:12:12

标签: javascript

我想只得到对象(猫,狗,鸟)的名字



/// objects from which I want to get a name ///
   

 var storage = [
    {cat: {name: "Garfield", count: 3443, price: 1000}},
    {bird: {name: "Eagle", count: 4042, price: 3000}},
    {dog: {name: "Rex", count: 1488, price: 2000}}
    ];

    function  getAllProductNames(storage) {
        var keys = [];
        for(var key in storage) {
            keys.push(key);
            if(typeof storage[key] === "object") {
                var subkeys = getAllProductNames(storage[key]);
                keys = keys.concat(subkeys.map(function(subkey) {
                    return key + "." + subkey;
                }));
            }
        }
        console.log(keys);
        return keys;
    }
    getAllProductNames(storage);




4 个答案:

答案 0 :(得分:2)

您可以使用Array#map映射对象的第一个键,以迭代数组并使用Object.values返回属性。

function  getAllProductNames(storage) {
    return storage.map(object => Object.values(object)[0].name);
}

var storage = [{ cat: { name: "Garfield", count: 3443, price: 1000 } }, { bird: { name: "Eagle", count: 4042, price: 3000 } }, { dog: { name: "Rex", count: 1488, price: 2000 } }  ];

console.log(getAllProductNames(storage));

答案 1 :(得分:2)

var storage = [
    {cat: {name: "Garfield", count: 3443, price: 1000}},
    {bird: {name: "Eagle", count: 4042, price: 3000}},
    {dog: {name: "Rex", count: 1488, price: 2000}}
    ];
var names = []; 
storage.map(function(a){
  names.push(Object.keys(a)[0]);
})
console.log(names );

答案 2 :(得分:2)

使用简单的for...in循环

var index = 0;
var keys = []
var storage = [
    {cat: {name: "Garfield", count: 3443, price: 1000}},
    {bird: {name: "Eagle", count: 4042, price: 3000}},
    {dog: {name: "Rex", count: 1488, price: 2000}}
    ];

for(index in storage) {
      keys.push(Object.values(storage[index])[0].name)
}
console.log(keys)

答案 3 :(得分:1)

如果您的每个存储对象都有多个产品,请尝试此操作

var allProduct = [];
storage.forEach((obj) => {allProduct.push(...Object.keys(obj))})
console.log(allProduct)