javascript - 获取值为数组的对象数组中的所有键
问题描述
我尝试将值是数组的对象数组中的所有键写入新数组。没有重复。javascript中最好的方法是什么,没有像lodash或underscore这样的库。我认为我的解决方案绝对是可以改进的。单个对象及其键是可变的,并不总是相同的。欢迎提出建议。
我的示例的预期输出应该是:[“stuff”,“type”,“misc”,“something”]
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]) 检查 value 是否为数组。
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)]
}, [])
推荐阅读
- android - Flutter AnimatedCrossFade 弄乱了小部件格式
- typescript - 为什么 SDK 资源在 @types/google-apps-script 中被视为可选资源?
- html - mat-table 中的列大小并读取包含 Array angular 的 Object
- c# - IsExternalStorageManager == true,但拒绝访问外部存储(Android 11)
- ios - 通过 ARKit 将 Apple Watch 用作取景器
- crash - 电脑死机显示HDMI无信号,必须拔掉重新启动
- android-studio - Android debug.keystore 命令不起作用?
- bash - 在过滤输出时执行另一个命令
- json - 在 JQ 中展开大数组并选择元素
- firebase - Flutter Firebase 函数:如何确保对可调用函数进行身份验证?