0

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?

1
  • it is unclear which function do you like to use after spreading. Commented Sep 18, 2019 at 15:14

4 Answers 4

4

Use destructuring in arguments

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

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

logArgs(civic)

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think this answers the question, but it's correct and I'm not sure the question is actually answerable...so have a +1!
This only works for the given object, doesn't the OP want a generic version for any object?
1
logArgs(...Object.values(civic))

Note that this would rely on the order of objects, which can be tricky

1 Comment

This is the solution I ended up using, thank you. Nina has an interesting approach too.
1

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);

2 Comments

Not fully following on how this is different from Juan's answer.
Had to look this up as well: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…* Ty again for interesting answer.
0

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)

1 Comment

I have shown the function parameter destructuring and object destructuring

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.