最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get property names of objects in array? - Stack Overflow

programmeradmin6浏览0评论

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']

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']
Share Improve this question edited May 23, 2017 at 12:09 CommunityBot 11 silver badge asked Jan 28, 2017 at 16:07 Aecio LevyAecio Levy 1551 silver badge9 bronze badges 1
  • 2 It's because you are getting the properties of the array, not the objects within it – Andrew Li Commented Jan 28, 2017 at 16:10
Add a ment  | 

8 Answers 8

Reset to default 6

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);

var testArray = [{
  name: "Jovem1",
  esteira: "Macaco"
}, {
  name: "Jovem",
  esteira: "Doido",
  horse: "Chimbinha"
}];

var propName = [];

testArray.forEach(function(o) {
  Object.keys(o).forEach(function(prop) {
    if (propName.indexOf(prop) < 0)
      propName.push(prop);
  });
});

console.log(propName);

You could try something like this:

 var testeArray = [
    {name: "Jovem1", esteira: "Macaco"},
    {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }
  ];

// The array in which we push the unique property names.
var properties = [];

testeArray.forEach(function(obj){
    for(var key in obj){
       if(obj.hasOwnProperty(key) 
          && properties.indexOf(key) === -1) { 
          // It's the first time we hit key. So push it to the array.
         properties.push(key);
       }
    }
});

console.log(properties);

First get all the properties from the array using Object.keys and then filter out to get the distinct ones

var testeArray = [
    {name: "Jovem1", esteira: "Macaco"},
    {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }
  ]

var properties = [];
testeArray.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        properties.push(k)
    });
});

var distProps = properties.filter(function(item, i, arr) {
    return arr.indexOf(item) === i;
})
console.log(distProps);

With ES6 you can use Set and spread syntax ... to do this.

var testeArray = [
  {name: "Jovem1", esteira: "Macaco"},
  {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }
];

var result = [...new Set([].concat(...testeArray.map(e => Object.keys(e))))]
console.log(result)

Ecmascript5 solution using Array.prototyp.reduce() and Object.keys() functions:

var testeArray = [
    {name: "Jovem1", esteira: "Macaco"},
    {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }
  ],
    keys = testeArray.reduce(function(r, o) {
        Object.keys(o).forEach(function (k) {
            if (r.indexOf(k) === -1) r.push(k);
        })
        return r;
    }, []);

console.log(keys);


Ecmascript6 solution using Set objects and Array.from function:

var testeArray = [
    {name: "Jovem1", esteira: "Macaco"},
    {name: "Jovem", esteira: "Doido", horse: "Chimbinha" }
  ],
    keys = testeArray.reduce(function(r, o) {
        var newSet = new Set(Object.keys(o));
        return new Set([...r, ...newSet]);
    }, new Set());

console.log(Array.from(keys));

[...r, ...newSet] within new Set([...r, ...newSet]) means that r and newSet are converted to arrays and concatenated.

function collectProperties(arrayOfObjects) {
  return arrayOfObjects.reduce(function(memo, object) {
    Object.keys(object).forEach(function(key) {
      if (memo.indexOf(key) === -1) { memo.push(key) };
    });
    return memo;
  }, []);
}

var testArray = [
  {name: "Jovem1", esteira: "Macaco"},
  {name: "Jovem", esteira: "Doido", horse: "Chimbinha"}
];

console.log(collectProperties(testArray));

So collectProperties(testeArray) returns ['name', 'esteira', 'horse'].

Or in CoffeeScript:

collectProperties = (arrayOfObjects) ->
  properties = []
  for object in arrayOfObjects
    for own property of object when property not in properties
      properties.push(property)
  properties

testArray = [
  {name: "Jovem1", esteira: "Macaco"}
  {name: "Jovem", esteira: "Doido", horse: "Chimbinha"}
]

console.log(collectProperties(testArray))
发布评论

评论列表(0)

  1. 暂无评论