如何获取数组中对象的属性名称? [英] How to get property names of objects in array?

查看:1373
本文介绍了如何获取数组中对象的属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的数组:

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"];

数组包含对象数组中对象的所有属性名称。我尝试了在JavaScript对象中找到的属性名称的表单数组,但结果是:

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


推荐答案

您可以使用 Array#forEach 并获取 Object的键。键 并收集对象中的名称。然后将键作为结果。

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与 Set 传播语法 ...

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

这篇关于如何获取数组中对象的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆