gpt4 book ai didi

javascript - 获取值为数组的对象数组中的所有键

转载 作者:行者123 更新时间:2023-12-01 15:55:36 24 4
gpt4 key购买 nike

我尝试将值是数组的对象数组中的所有键写入一个新数组。无重复。在没有 lodash 或下划线等库的情况下,javascript 中最好的方法是什么。我认为我的解决方案绝对可以改进。单个对象及其键是可变的,并不总是相同的。欢迎提出建议。

我的示例的预期输出应该是:[ “东西”, “类型”, “杂项”, “某物”]

const items = [{
name: "Joe",
occupied: "no",
mobile: "yes",
treatment: "no",
date: "29-03-2020",
age: "15",
stuff: ["A", "B", "C"],
type: ["1", "2"]
},
{
name: "Jack",
occupied: "yes",
mobile: "no",
treatment: "no",
date: "02-03-2020",
age: "20",
stuff: ["A", "B", "C", "D", "E"],
type: ["8", "6"],
misc: ["otherStuff", "someStuff"]
},
{
name: "Jane",
occupied: "no",
mobile: "yes",
treatment: "yes",
date: "15-02-2020",
age: "28",
stuff: ["C", "D", "E"],
type: ["4", "7"],
something: ["xxx", "ccc"]
}
];


function getKeysWithArrayValues(myArray) {
const result = [];
myArray.forEach(item => Object.entries(item).forEach(itm => itm.filter(Array.isArray).forEach(x => result.push(itm.slice(0, 1)))));
return flatArray(result)
};

function flatArray(array) {
return array.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatArray(val)) : acc.concat(val), []);
};
const ttt = getKeysWithArrayValues(items);
const flat = Array.from(new Set(ttt))
console.log(flat);

最佳答案

这是我的解决方案,希望对您有所帮助。算法很清楚,我想没有必要解释太多。我们只是使用 reduce 方法遍历一个数组,最后构建只包含符合我们要求的键的新数组。

Array.isArray(rec[key]) 检查值是否为数组。

acc.indexOf(key) < 0 检查键是否已经包含在前面步骤之一的结果数组中。

const arr_ = items
.reduce((acc, rec) => {
return [...acc, ...Object.keys(rec).filter(key => Array.isArray(rec[key]) && acc.indexOf(key) < 0)]
}, [])

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

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