【发布时间】:2020-03-29 21:03:48
【问题描述】:
我尝试将值是数组的对象数组中的所有键写入新数组。没有重复。 什么是 javascript 中最好的方法,没有像 lodash 或 underscore 这样的库。我认为我的解决方案绝对是可以改进的。单个对象及其键是可变的,并不总是相同的。 欢迎提出建议。
我的示例的预期输出应该是: [ “东西”, “类型”, “杂项”, “某物” ]
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);
【问题讨论】:
-
请添加您的解决方案。
-
@nina 将代码编辑为可运行的 sn-p
标签: javascript arrays json object