我想映射一个对象并将值作为道具传递
我正在处理一个 redux 项目,我最初有一个对象数组,因此迭代它们更容易,但我被要求将我的初始状态转换为 js 对象,但我很难重构它
// Original State
lists = [
{
id: 0,
title: "List1",
cards: [
{
id: 0,
title: "card1",
user: "ali"
}
]
},
{
id: 1,
title: "List2",
cards: [
{
id: 1,
title: "card1",
user: "ahmed"
},
{
id: 2,
title: "card2",
user: "khalid"
}
]
}
];
// This is where I map over the card and send the values as props
cards.map(card => (
<TodoCard
key={card.id}
title={card.title}
listId={listId}
cardId={card.id}
user={card.user}
/>
));
代码工作正常,但是如果将数组转换为下面给出的js对象,我该如何迭代
lists = [
{
id: 0,
title: "List1",
cards: {
cardDetail: {
id: 0,
title: "card1",
user: "ali"
}
}
},
{
id: 1,
title: "List2",
cards: {
cardDetail: [
{
id: 1,
title: "card1",
user: "ahmed"
},
{
id: 2,
title: "card2",
user: "khalid"
}
]
}
}
];
你不能那样做。你要么需要使用
list = [{object}, {object}];
//or
list = {myList: [{object}, {object}]}
你不能只写
list = {{object}, {object}}
因为它的语法无效。
看看什么是以及如何使用对象和数组
https://www.w3schools.com/js/js_objects.asp
https://www.w3schools.com/js/js_arrays.asp
cards:{
cardDetail:
{
id:1,
title:"card1",
user:"ahmed"
},
{
id:2,
title:"card2",
user:"khalid"
}
}
}
您可以使用Object.keys()
进行迭代,这将提供所有密钥,然后执行forEach
。
Object.keys(cards).forEach((key,index) => {
// key: the name of the object key.... cardDetail here
// index: the ordinal position of the key within the object
// value : cards[key]... value of the object.
});
您还需要对value : cards[key]
进行循环,因为它有多个对象,这似乎效率低下,因此如果可能的话,最好设计数据对象