简体   繁体   中英

Destructuring argument for key along with object in javascript

How can I get the passed in object course along with the id key using destructuring the argument as in following code snippet ?

...
return (
    <div>
      {course.map(course => {
        return <Course key={course.id} course={course} />;
      })}
    </div>
  );

For instance I've tried like(see below) this, but its not valid

...
return (
    <div>
      {course.map(({id} = course) => {
        return <Course key={id} course={course} />;
      })}
    </div>
  );

The object for reference

const course = [
    {
      name: "Half Stack application development",
      id: 1
    },
    {
      name: "Node.js",
      id: 2
    }

Are there any way to do this or is it not possible yet?

Destructure id and spread the rest

course.map( ({ id, ...item }) => (
     <div id={id}> {item.foo} </div>   
))

You can't destruct an object into its an element and itself.

It could be better destruct item in the callback function like below.

 console.log('-------Only get rest obj------'); const courses = [{ name: "Half Stack application development", id: 1 }, { name: "Node.js", id: 2 }]; courses.forEach(({id, ...item}) => console.log('rest obj:', item)); console.log('----Get full obj and destruct---------'); courses.forEach(item => { const { id } = item; console.log('id:', id); console.log('item:', item); });

return (
    <div>
      {course.map(item => {
        return <Course key={item.id} course={item} />;
      })}
    </div>
  );

You are trying to use the course variable again inside map function.

Rename outer most variable from course to courses.

return (
    <div>
      {courses.map(course => {
        return <Course key={course.id} course={course} />;
      })}
    </div>
  );

Consider below example

return (
    <div>
      {course.map(({ id, ...course }) => {
        return <Course key={id} course={course} />;
      })}
    </div>
  );

It does gets us the id but course object does have all the keys of the original object(ie, it doesn't have the id now).

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