0

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() }
Charklewis
  • 4,427
  • 4
  • 31
  • 69
  • 1
    Do you want something like this? [Is it possible to destructure onto an existing object? (Javascript ES6)](https://stackoverflow.com/q/29620686) – Nick Parsons Jun 23 '20 at 15:06

2 Answers2

2

You could probably try something like this:

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

You would need person defined as an object beforehand.

Yathi
  • 1,011
  • 1
  • 12
  • 21
  • Does this approach scale if `person` isn't an empty object? For example if it is defined as `let person = { age: 20 }` before running your suggested code. – Charklewis Jun 23 '20 at 16:51
  • Yes it does. I updated the answer. The object needs to be defined. If it has the keys, they will be replaced. If it doesn't have the keys, they will get added to it. – Yathi Jun 30 '20 at 13:50
1

You can use Object.assign for this.. For example.

let person = { firstName: 'John', lastName: 'Doe', age: 67, //etc... }

let newPerson = Object.assign(person, getNames()) 

console.log(newPerson)

// Expected output: `{ firstName: 'newFirstName', lastName: 'newLastName', age: 67, etc... }` 

You can view more on Object.assign here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

radlaz
  • 298
  • 4
  • 16