Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript remove keys from object not in an Array

Suppose I have a list of objects with many keys and I want to keep only certain keys from them. This is how I am doing it.

The Problem with other good solutions on SO are that if a key is not present in the keys to keep it still adds a key, value where the value is undefined.

let data = [{
   'a': 1,
   'b': 2,
   'c': 3
 }, 
 {
   'a': 1,
   'c': 3,
   'd': 4
 }]

const keys_to_keep = ['a', 'b']

data = data.map((obj) => {
  Object.keys(obj).forEach(function(key) {
    if(!keys_to_keep.includes(key))
      delete obj[key]
  });
  return obj;
})

Output :

[ { a: 1, b: 2 }, { a: 1} ]

Is there a better way to get this done. Any help is appreciated.

like image 943
Akshay Hazari Avatar asked Sep 01 '26 22:09

Akshay Hazari


2 Answers

A couple of improvements.

  1. You're using .map() which creates a new array, but then you're just assigning it to the old variable. So, you apparently don't need to create a new array at all, you can just iterate the one you have and modify it.

  2. Put the properties you want to keep in a Set instead of an Array for potentially faster lookup.

  3. for/of loops are generally favored over .forEach() loops because of better flow control options (break, continue, return, etc...) and more opportunities for compiler optimization.

let kv = [{
   'a': 1,
   'b': 2,
   'c': 3
 }, 
 {
   'a': 1,
   'b': 2,
   'c': 3,
   'd': 4
 }]

const l = new Set(['a', 'b']);

for (let obj of kv) {
    for (let prop of Object.keys(obj)) {
       if (!l.has(prop)) {
           delete obj[prop];
       }
    }
}

console.log(kv);
like image 60
jfriend00 Avatar answered Sep 04 '26 12:09

jfriend00


You can use Object.fromEntries, after map and filter to keep only the relevant keys:

let data = [{'a': 1,'b': 2,'c': 3},{'a': 1,'c': 3,'d': 4}]
const keys_to_keep = ['a', 'b']

var result = data.map(obj =>
    Object.fromEntries(keys_to_keep.map(key => 
        obj.hasOwnProperty(key) && [key, obj[key]]
    ).filter(Boolean))
);

console.log(result);
like image 34
trincot Avatar answered Sep 04 '26 11:09

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!