嗨,我有一个 redux 状态作为对象
const state= {
posts: {
byId:{
"8xf0y6ziyjabvozdd253nd":{
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2,
comments: ["894tuq4ut84ut8v4t8wun89g", "8tu4bsun805n8un48ve89"]
},
"6ni6ok3ym7mf1p33lnez":{
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0,
comments:[]
}
},
allIds:["8xf0y6ziyjabvozdd253nd","6ni6ok3ym7mf1p33lnez"]
}
}
我想让它把它转换成一个数组,这样我就可以在 React 中使用它。它应该看起来像
posts: [
{
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2,
comments: ["894tuq4ut84ut8v4t8wun89g", "8tu4bsun805n8un48ve89"]
},
{
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0,
comments:[]
}
]
怎么做到的?我的尝试不起作用
const postsList = state.posts.byId.map(post=>(
{
id: post.id,
timestamp: post.timestamp,
title: post.title,
body: post.body,
author: post.author,
category: post.category,
voteScore: post.voteScore,
deleted: post.deleted,
commentCount:post.commentCount,
comments: post.comments.map(id=>id)
// }
))
再次尝试无效
const postOrder = state.posts.allIds
const a = {posts:postOrder.map((post)=>(
{
post,
Object.keys(state.posts.byId.reduce(()=>{
}))
}
))}
现在我尝试在互联网上搜索我看到一些人使用 loaddash 库,有些人甚至使用 reduce 方法但是自从
I am not a javascript developer
,这对我来说太难了。我是一名 Python 开发人员
最佳答案
const state= {
posts: {
byId:{
"8xf0y6ziyjabvozdd253nd":{
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2,
comments: ["894tuq4ut84ut8v4t8wun89g", "8tu4bsun805n8un48ve89"]
},
"6ni6ok3ym7mf1p33lnez":{
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0,
comments:[]
}
},
allIds:["8xf0y6ziyjabvozdd253nd","6ni6ok3ym7mf1p33lnez"]
}
}
const posts = Object.values(state.posts.byId)
console.log(posts);
关于javascript - 在 Redux 中将对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878618/