Search code examples
javascriptarraysjavascript-objectsdestructuring

To destructure a particular property of each object that is nested in an array of objects


I'm wondering if I can destructure this array of objects

 const course = {
        id: 1,
        name: 'Half Stack application development',
        parts: [
            {
                name: 'Fundamentals of React',
                exercises: 10,
                id: 1
            },
            {
                name: 'Using props to pass data',
                exercises: 7,
                id: 2
            },
            {
                name: 'State of a component',
                exercises: 14,
                id: 3
            },
        ]
    }

and save the property exercises in a variable, I dont know if we would ever do this, just want to know how and if we can destructure object properties in an array of objects

@ggrlen Here's the array

const arr = [{
    name: 'State of a component',
    exercises: 14,
    id: 3
}];

I want to destruct the object in this array, to extract value of exercises property into a variable, thanks for the reply btw.


Solution

  • Converting my comments into an answer to illustrate various destructuring patterns:

    const course = {
      id: 1,
      name: 'Half Stack application development',
      parts: [
        {
          name: 'Fundamentals of React',
          exercises: 10,
          id: 1
        },
        {
          name: 'Using props to pass data',
          exercises: 7,
          id: 2
        },
        {
          name: 'State of a component',
          exercises: 14,
          id: 3
        },
      ]
    };
    
    console.log(course.parts.map(e => e.exercises));
    console.log(course.parts.map(({exercises: e}) => e)); // rename to `e`
    
    let {parts: [{exercises}]} = course; // extract nested property
    console.log(exercises); // 10
    
    ({parts: [,{exercises}]} = course); // second elem
    console.log(exercises); // 7
    
    ({parts: [,,{exercises}]} = course); // third elem
    console.log(exercises); // 14

    const arr = [
      {
        name: 'State of a component',
        exercises: 14,
        id: 3
      },
      {
        name: 'State of a component',
        exercises: 1422,
        id: 3
      }
    ];
    
    const [{exercises}] = arr;
    console.log(exercises); // 14
    
    let [, ...rest] = arr; // extract everything after the first
    console.log(rest);
    
    // from second elem, extract `exercises` as `ex`, 
    // extract object properties other than `exercises` as `others`
    const [,{exercises: ex, ...others}] = arr;
    console.log(ex); // 1422
    console.log(others);