1

I have an object with some keys

{
    a: 1,
    b: 2,
    c: 3,
    .....
}

I'm looking for the easiest way to keep only specific keys from the object

For example I want to clone this object and keep only "a" and "b"

The first object doesn't have specific keys, so I can't just delete "c"

I'm looking for the easiest way

Thanks

Michalis
  • 5,647
  • 8
  • 44
  • 66

1 Answers1

1

You can use .reduce on Array of keys (as strings).
You can check for .hasOwnProperty to validate the existing of the key before adding it to the new object.

Example:

const obj = {
  a: 1,
  b: 2,
  c: 3,
}


const newObj = ['a', 'c', 'z'].reduce((result, key) => {
  if (obj.hasOwnProperty(key)) {
    result[key] = obj[key];
  }
  return result;
}, {});

console.log(newObj)
Sagiv b.g
  • 26,049
  • 8
  • 51
  • 86
  • with this example if i don't give "a" to the first object... then i will have a = undefined. But i want only the existing properties – Michalis Dec 30 '17 at 13:49
  • @Michalis You can check the existing of the property before you assign it. for example `if (obj.hasOwnProperty(key))`. I've updated my answer to reflect this – Sagiv b.g Dec 30 '17 at 13:53