4

Say I have an object:

myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2', three: '3'} // (Edited) Added one more key here :)
};

I want a copy of this object without certain keys to a new object in a way that the output is as below:

newObj = { 
      name: 'Luke',
      age: 12,
      one: '1',
      two: '2'
    };

I have seen examples of destructing but I wanted to know if it is possible with nested objects. Is something like this doable using destructuring or if not what would be the most efficient way to do this.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
Nibin
  • 3,922
  • 2
  • 20
  • 38

3 Answers3

5

One way to achieve this with destructure-like syntax would be like this:

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2', three : '3'}
};


const newObj = {
  /* Copy over values from "myObj" to equivalent keys in "newObj" */
  name : myObj.name,
  age : myObj.age,

  /* Spread keys "one" and "two" of the nested "others" object into "newObj" */
  ...({one, two} = myObj.others, {one, two})
}

console.log(newObj)
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
4

For completeness, an iife approach is possible. It works by creating an arrow function that takes as parameters keys you want to keep. In the function body, spread nested objects as desired.

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2'}
};

const newObj = (
  ({name, age, others}) => ({name, age, ...others})
)(myObj);

console.log(newObj);
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Thanks for the response. What if I need only the key 'one' from the nested object. Is this possible? I have updated the question. – Nibin May 08 '19 at 04:32
  • You could use `Object.assign({}, {name, age}, {one: others.one})` as the function body. However, it sounds like you're looking for a general function that will take something like an array of keys to keep and will recursively copy everything (possibly with flattening)?. Can you specify your requirements a bit further? Otherwise, it's whack-a-mole. – ggorlen May 08 '19 at 04:45
2

For the object of unknown depth you can try using recursion.

  • Create a function which takes an object and array of keys to be removed as arguments.
  • Create a helper(which takes 1 object as parameter) function inside main and create empty object.
  • Loop through the properties of obj using for..in.
  • check if key is not present in the array of keys to be removed then
    • Check if the value is object then call the function recursively
    • If its not object then add it to the result obj.
  • At last return the result object.

The code will convert the object of unknown depth to a plain object and you can also remove keys from nested objects.

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2'}
};
const removed = ['height','weight','one'];

function removeKeys(obj,removed){
  const res = {};
  function helper(obj){
    for(let key in obj){
      if(!removed.includes(key)){
        if(typeof obj[key] === "object"){
          helper(obj[key]);
        }
        else res[key] = obj[key]
      }
    }
    
  }
  helper(obj)
  return res;
}

const res = removeKeys(myObj,removed);
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Thanks for the response. What if I need only the key 'one' from the nested object of known depth. Is this possible? I have updated the question – Nibin May 08 '19 at 04:37
  • @Outlooker The function I created takes an array as argument. This array will contain all the keys to be removed from the any level of nested object. Do you want the function which gets all the keys in array? – Maheer Ali May 08 '19 at 04:40
  • The function you provided works first class. But I just wanted to know if this is possible using destructuring if the object is of known depth – Nibin May 08 '19 at 04:43
  • @Outlooker I think there is no way. Because there is no way to destructure all the properties of the nested object. – Maheer Ali May 08 '19 at 04:47
  • Thanks for the help @Maheer. Appreciated. :) – Nibin May 08 '19 at 05:14