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

Remove objects from each object in an array of objects

I want to improve the table performance with a large dataset by removing all nested objects which the table doesn’t use. I don’t want to name the keys because they will vary from dataset to dataset. This needs to be a reusable helper function that removes objects based on typeof rather than a key.

Example data:

const data = [
  { test: 1, notes: [] },
  { test: 2, notes: [] },
  { test: 3, notes: [] }
];

expected result

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

[
  { test: 1 },
  { test: 2 },
  { test: 3 }
];

What I’ve tried:

  const simpleRows = (arr) => {
    var rows = arr.map(({ notes, ...keepAttrs }) => keepAttrs);
    return rows;
  };

  const rows = simpleRows(data) // This works but I have hardcoded the key 'notes' which I don't want

What is the most efficient way to remove all objects from each object in an array of objects in a large dataset (~10000 objects in the array) without hardcoding the key, and without an external library?

Thanks

>Solution :

You can filter the entries of each object and create a new object from the filtered entries:

const data = [
  { test: 1, notes: [] },
  { test: 2, notes: [] },
  { test: 3, notes: [] }
]
const result = data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => !Array.isArray(v))))
console.log(result)
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