Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get property names of objects in array?

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']
like image 412
Aecio Levy Avatar asked Feb 05 '23 05:02

Aecio Levy


2 Answers

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);
like image 187
Nina Scholz Avatar answered Feb 07 '23 19:02

Nina Scholz


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);
like image 20
Redu Avatar answered Feb 07 '23 18:02

Redu