简体   繁体   中英

Destructure an Object Like An Array in JS?

Given the following code:

const civic = {make: 'Honda', model: 'Civic'};

function logArgs(make, model) {
  console.log(make);
  console.log(model)
}

I want to do this:

logArgs(...civic);

instead of:

logArgs(civic.make, civic.model);

I get:

(index):39 Uncaught TypeError: Found non-callable @@iterator

Is there some way to destructure objects like arrays, or is what I am trying to do impossible?

Use destructuring in arguments

 const civic = {make: 'Honda', model: 'Civic'}; function logArgs({make, model}) { console.log(make); console.log(model) } logArgs(civic) 

logArgs(...Object.values(civic))

请注意,这将取决于对象的顺序,这可能会很棘手

For spreading, you need to implement a Symbol.iterator for the object, because objects do not have a built in iterator.

This approach takes the values only, but any other approach may work, like to return the entries.

 function logArgs([make, model]) { console.log(make); console.log(model) } const civic = { make: 'Honda', model: 'Civic' }; civic[Symbol.iterator] = function* () { yield Object.values(civic); }; logArgs(...civic); 

In destructuring the object parameter civic, we get a more concise function, Or you can just destructure civic to assign diffrent variables as shown below

 const civic = {make: 'Honda', model: 'Civic'}; const { make, model, year = "2019" } = civic; console.log(make); console.log(year); function logArgs({make, model}) { console.log(make); console.log(model) } logArgs(civic) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM