Search code examples
javascriptjavascript-objects

Destructure object and assign to another object in one line


Is there a way to do the following in one line?

let person = {}

const { firstName, lastName } = getNames()
//or this
//const { firstName, lastName } = await getNames()

person.firstName = firstName
person.lastName = lastName

I often do this when coding, and hoping there is a shortcut. I can not see any hints on how to do this on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment.

I was trying something like the below however, it overrides the other properties in the object.

let person = { age: 20 }
person = { ...getNames() }

I don't think this will work well with async/await functions either, as they return a promise.

let person = { age: 20 }
person = { ...await getNames() }

Solution

  • You could probably try something like this:

    ({firstName: person.fistName, lastName: person.lastName} = getNames());
    

    You would need person defined as an object beforehand.