gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:28:02 25 4
gpt4 key购买 nike

我正在创建并返回这个对象,其属性源自一个深度嵌套的对象:

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

最佳答案

您可以使用 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))

关于javascript - 使用 ES6 从深度嵌套对象中的值创建平面对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48188085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com