gpt4 book ai didi

javascript - 获取数组对象中第一个对象的键

转载 作者:行者123 更新时间:2023-11-30 10:59:48 24 4
gpt4 key购买 nike

我正在尝试从一组对象中获取一组(不同的)键。

arr =[
{id: 1, desc: "", name: "", objectives: Array(3), …},
{id: 2, desc: "", name: "", objectives: Array(3), …},
{id: 3, desc: "", name: "", objectives: Array(3), …},
{id: 4, desc: "", name: "", objectives: Array(3), …},
]

期望的输出是 [id, desc, name, objectives]。我试过:

Object.keys(arr)[0]
// output [{id: 1, desc: "", name: "", objectives: Array(3), …}]

arr.flatMap(Object.key)
// output ["id", "desc", "name", "objectives", "id", "desc", "name", "objectives", "id", "desc", "name", "objectives", "id", "desc", "name", "objectives"]

如果我在搜索 SO 时错过了这个问题的答案,我很抱歉。非常感谢任何帮助。

最佳答案

您可以使用 Set 来清除重复项:

const arr = [
{id: 1, desc: "", name: "", objectives: []},
{id: 2, desc: "", name: "", objectives: []},
{id: 3, desc: "", name: "", objectives: []},
{id: 4, desc: "", name: "", objectives: []},
];

const keys = [...new Set(arr.flatMap(Object.keys))];

console.log(keys);

关于javascript - 获取数组对象中第一个对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313777/

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