Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to improve my current solution would be greatly appreciated. The keys within the objects are dynamic and not always consistent.
The desired output based on my example should be: [ "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);