解构嵌套在对象数组中的每个对象的特定 属性

To destructure a particular property of each object that is nested in an 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
            },
        ]
    }

并将 属性 exercises 保存在一个变量中,我不知道我们是否会这样做,只是想知道我们如何以及是否可以解构对象数组中的对象属性

@ggrlen 这是数组

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

我想破坏这个数组中的对象,将 exercises 属性 的值提取到一个变量中,谢谢你的回复 btw。

将我的评论转换为答案以说明各种解构模式:

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