Quero obter apenas os nomes de objetos (gato, cachorro, pássaro)
/// 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);
Você pode mapear a primeira chave dos objetos usando Array#map
para iterar a matriz e retornar a propriedade com 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));
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras