Akshay Hazari
Akshay Hazari

Reputation: 3267

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.

Upvotes: 6

Views: 6336

Answers (2)

trincot
trincot

Reputation: 350272

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);

Upvotes: 3

jfriend00
jfriend00

Reputation: 707326

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);

Upvotes: 10

Related Questions