Thore
Thore

Reputation: 1838

Destruct object properties in array.map() and keep object as parameter

Is it possible to destruct the properties of an object while keeping the object as a parameter inside an array.map() function?

Based on this question I tried the following but failed (parsing error)

  this.state.files.map(((file, {param1, param2} = file), i) => (
    <div key={i}>
      <p>{param1}</p>
      <button onClick={this.editFile(file)} />
    </div>
  )

Upvotes: 1

Views: 2818

Answers (2)

user4639281
user4639281

Reputation:

One way to achieve this would be to use the default parameters syntax, like so:

const test = (input, { a, b } = input) => [ a, b ]
console.log(test({ a: 1, b: 2 })) // [ 1, 2 ]

No second parameter is passed to the function above, so the second parameter defaults to the first parameter, then it is destructed.

The parameter can only be used after it has been declared, so this won't work:

const test = ({ a, b } = input, input) => [ a, b ]
console.log(test(undefined, { a: 1, b: 2 }))
// Uncaught ReferenceError: input is not defined at test

This can also only work if no parameter is passed, so in the case of a callback being passed to Array#map, you must declare all of the parameters being passed so that you can declare the default parameter.

With your example it would look like this:

this.state.files.map((file, i, files, { param1, param2 } = file) => (
  <div key={i}>
    <p>{param1}</p>
    <button onClick={this.editFile(file)} />
  </div>
))

Upvotes: 2

Gaudam Thiyagarajan
Gaudam Thiyagarajan

Reputation: 1052

Instead of using lambda component make it a functional block like so

  this.state.files.map(((file, i) => {
    const {param1, param2} = file;
    return (
      <div key={i}>
        <p>{param1}</p>
        <button onClick={() => this.editFile(file)} />
      </div>
    )}
  )

Upvotes: 1

Related Questions