Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the easiest way to get required keys from array of objects

I required to extract unique keys from array, leaving unwanted keys. here is my try it works fine.
But looking for the easiest way.

Live demo

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading