I required to extract unique keys from array, leaving unwanted keys. here is my try it works fine.
But looking for the easiest way.
const data = [{
"year": "2021",
"europe": 5,
"namerica": 2.5,
"asia": 1
}, {
"year": "2022",
"europe": 2.6,
"namerica": 6.7,
"asia": 2.2
}, {
"year": "2023",
"europe": 4.8,
"namerica": 1.9,
"asia": 4.4
}];
const uniqueLables = [];
const omit = ["year"]
for (let i = 0; i < data.length; i++) {
for (const [key, value] of Object.entries(data[i])) {
if (!uniqueLables.includes(key)) {
if (!omit.includes(key)) {
uniqueLables.push(key);
}
}
}
}
console.log(uniqueLables) // => ['europe', 'namerica', 'asia']
>Solution :
If you don’t need your omit keys to be dynamic (ie: in an array), you can merge every object together (using Object.assign()) to get an object with all keys, and then extract an object excluding year using destructuring assignment and take the keys of that:
const data = [{ "year": "2021", "europe": 5, "namerica": 2.5, "asia": 1 }, { "year": "2022", "europe": 2.6, "namerica": 6.7, "asia": 2.2 }, { "year": "2023", "europe": 4.8, "namerica": 1.9, "asia": 4.4 }];
// v-- omit
const {year, ...r} = Object.assign({}, ...data);
const keys = Object.keys(r);
console.log(keys);
With an array of omit keys, you can replace the destructuring with .filter() on Object.keys():
const data = [{ "year": "2021", "europe": 5, "namerica": 2.5, "asia": 1 }, { "year": "2022", "europe": 2.6, "namerica": 6.7, "asia": 2.2 }, { "year": "2023", "europe": 4.8, "namerica": 1.9, "asia": 4.4 }];
const omit = ['year'];
const merged = Object.assign({}, ...data);
const keys = Object.keys(merged).filter(key => !omit.includes(key));
console.log(keys);