0

For example:

const obj = {name: 'jack', age: 18, gender: 'male'}
const {name, age} = obj
const obj2 = {name, age}

I want some key-value of a obj to make up a new obj, above is three line codes , I want to know if there is a way more concise? in one line?

Dearest
  • 107
  • 1
  • 7
  • `const obj2 = {name: 'jack', age: 18}`? – Luca Kiebel Sep 19 '18 at 12:20
  • 1
    I am not sure why you would do that, but... const obj2 = { name, age } = { name: 'jack', age: 18, gender: 'male' }; – Zunino Sep 19 '18 at 12:22
  • @Zunino In a react framework i need to pick up some props from a bigger object, it can't work, `obj2` will has both the three props – Dearest Sep 19 '18 at 12:28
  • 1
    @Zunino No, that does not work: it assign the original object to `obj2`, and it does assign to global variables. – Bergi Sep 19 '18 at 12:43
  • @Bergi You're right. As for the original question, I couldn't come up with anything that wouldn't look cumbersome and worse than the original code. For instance, take a look at this monstrosity: Object.fromEntries(Object.entries(obj).filter(e => ["name", "age"].includes(e[0]))) --not to mention there is no support for Object.fromEntries yet. I'm out of ideas for now. Sorry. – Zunino Sep 19 '18 at 12:59
  • 1
    @Zunino See the second duplicate link – Bergi Sep 19 '18 at 13:02

0 Answers0