Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to copying a few keys from a nested object by destructuring

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.

like image 829
Outlooker Avatar asked Dec 17 '22 17:12

Outlooker


2 Answers

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)
like image 142
Dacre Denny Avatar answered Apr 14 '23 16:04

Dacre Denny


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);
like image 26
ggorlen Avatar answered Apr 14 '23 14:04

ggorlen