使用ES6从深层嵌套对象中的值创建平面对象

时间:2018-01-10 13:00:26

标签: javascript ecmascript-6

我使用源自深层嵌套对象的属性创建并返回此对象:

const mapStateToProps = (state) => ({
  firstName: state.currentUser.obj.firstName,
  lastName: state.currentUser.obj.lastName,
  email: state.currentUser.obj.email,
})

另一种方法是:

const mapStateToProps = (state) => {
  const {
    obj: {firstName, lastName, email},
  } = state.currentUser;

  return {
    firstName,
    lastName,
    email,
  };
}

我对第一个例子感到非常满意,但是找到一种方法来跳过每一行重复state.currentUSer.obj会很好。

除了给定的例子,有没有更简洁的方法来实现上述目的?

输入对象:

const state = {
  currentUser: {
    isUpdatingAccount: false,
    isUpdatingFavouriteColor: false,
    obj: {
      firstName: null,
      lastName: null,
      email: null,
      favoriteColor: null,
      favoriteTeam: null,
    },
  },    
}

1 个答案:

答案 0 :(得分:4)

您可以使用nested destructuring获取所需的属性:



const state = {
  currentUser: {
    isUpdatingAccount: false,
    isUpdatingFavouriteColor: false,
    obj: {
      firstName: null,
      lastName: null,
      email: null,
      favoriteColor: null,
      favoriteTeam: null,
    },
  },    
}

const mapStateToProps = ({ currentUser: { obj: { firstName, lastName, email }}}) => ({
  firstName,
  lastName,
  email
})

console.log(mapStateToProps(state))




您还应该添加默认值作为回退,以防止在缺少结构部分的情况下出现错误:



const state = {
  currentUser: {
    isUpdatingAccount: false,
    isUpdatingFavouriteColor: false
    // I've removed obj as an example with default fallback
  },    
}

const mapStateToProps = ({ currentUser: { obj: { firstName, lastName, email } = {}} = {}}) => ({
  firstName,
  lastName,
  email
})

console.log(mapStateToProps(state))