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

巧了我就是萌 提交于 2019-12-24 11:44:09

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/54085341/destruct-object-properties-in-array-map-and-keep-object-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!