gpt4 book ai didi

javascript - 如何获取数组中对象的属性名称?

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:47 27 4
gpt4 key购买 nike

这是我的数组:

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

从上面,我想得到一个这样的数组:

var propertyName = ["name", "esteira", "horse"];

数组包含对象数组中对象的所有属性名称。我试过 Form array of property names found in a JavaScript Object但结果是:

['0', '1']

最佳答案

您可以使用 Array#forEach 迭代数组并使用 Object.keys 获取 key 并收集对象中的名称。然后把 key 作为结果。

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

关于javascript - 如何获取数组中对象的属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41911878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com