我有一个从地图上获得的字符串,我想将其转换为变量,这是一个完整的示例: 1.我有以下项目清单:
const Fruits = [
{
name: 'Apple',
width: 100,
height: 100,
shape: 'apple',
},
{
name: 'Banana',
width: 10,
height: 100,
shape: 'banana',
},
]
const Fruits1 = [
{
name: 'Orange',
width: 100,
height: 100,
shape: 'orange',
},
{
name: 'Lemon',
width: 10,
height: 100,
shape: 'lemon',
},
]
const items = [
{
name: 'Fruits',
abbr: 'A',
},
{
name: 'Fruits1',
abbr: 'b',
},
]
const listItems = items.map((item, index) =>
<Item
key={index}
newList={item.name} // I need this one to become variable and not to evaluate into string
{...props}
/>
);
有什么建议吗?
我期望这个结果:
const listItems = items.map((item, index) =>
<Item
key={index}
newList={Fruits} // I need this one to become variable and not to evaluate into string
{...props}
/>
);
N.B:第一个项目的item.name为“水果”,第二个项目为“ Fruits1”,依此类推...
答案 0 :(得分:1)
如果我的理解正确,那么您想使用项目名称从Fruit集合中获取数据。这是一种简单的方法。
const listItems = items.map((item, index) =>
<Item
key={ index }
newList = { Fruits.find(fruit => fruit.name === item.name) } // I need this one to become variable and not to evaluate into string
{ ...props }
/>
);
答案 1 :(得分:1)
您似乎需要重命名items
JSON对象中的密钥。
您可以尝试这样做,
items.forEach(item=>{
item.Fruits = item.name
delete item.name
})
输入:
[
{
name: 'Apple',
abbr: 'A',
},
{
name: 'Banana',
abbr: 'b',
},
]
输出:
[
{
abbr: "A" ,
Fruits: "Apple"
}
{
abbr: "b" ,
Fruits: "Banana"
}
]
答案 2 :(得分:0)
尝试一下:
const Fruits = [
{
name: 'Apple',
width: 100,
height: 100,
shape: 'apple',
},
{
name: 'Banana',
width: 10,
height: 100,
shape: 'banana',
},
]
const items = [
{
name: 'Apple',
abbr: 'A',
},
{
name: 'Banana',
abbr: 'b'}
]
const result = items.map((ele, i) => ({key:i, newList:Fruits.find(r=>r.name===ele.name) ,...ele}) );
console.log(result);
答案 3 :(得分:0)
仅当您有两个数组时,此代码才是:Fruits和Fruits1,这是我从您的问题中了解的需要列表的内容。希望我回答了你的问题。
const listItems = items.map((item, index) => {
const Fruits = Fruits.find(fruit => fruit.name === item.name);
if (!Fruits) {
Fruits = Fruits1.find(fruit => fruit.name === item.name);
}
return (
<Item
key={index}
newList={Fruits} // I need this one to become variable and not to evaluate into string
/>
);
});