Here is my array:
var testeArray = [
{name: "Jovem1", esteira: "Macaco"},
{name: "Jovem", esteira: "Doido", horse: "Chimbinha"}
];
From the above, I would like to get a array like this:
var propertyName = ["name", "esteira", "horse"];
The array contains all the property names of the objects in the array of objects. I tried Form array of property names found in a JavaScript Object but the result was:
['0', '1']
You could iterate the array with Array#forEach
and get the keys with Object.keys
and collect the names in an object. Then take the keys as result.
var testeArray = [{name: "Jovem1", esteira: "Macaco"}, {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }],
names = Object.create(null),
result;
testeArray.forEach(function (o) {
Object.keys(o).forEach(function (k) {
names[k] = true;
});
});
result = Object.keys(names);
console.log(result);
ES6 with Set
and spread syntax ...
var array = [{name: "Jovem1", esteira: "Macaco"}, {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }],
names = [...array.reduce((s, o) => (Object.keys(o).forEach(k => s.add(k)), s), new Set)];
console.log(names);
You can very simply do as follows; I think it's probably the most efficient code so far.
var testArray = [
{name: "Jovem1", esteira: "Macaco"},
{name: "Jovem", esteira: "Doido", horse: "Chimbinha"}
],
props = Object.keys(testArray.reduce((o,c) => Object.assign(o,c)));
console.log(props);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With