I try to write all keys in an array of object whose values are arrays into a new array. Without duplicates. What is the best way in javascript, without libraries like lodash or underscore. I think that my solution is definitely improvable. The single objects and their keys are variable and not always identical. Suggestions welcome.
The intended output tom 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);