gpt4 book ai didi

javascript - 将来自变量的字符串转换为另一个变量

转载 作者:行者123 更新时间:2023-11-30 13:58:09 24 4
gpt4 key购买 nike

我有一个从 map 中获取的字符串,我想将其转换为一个变量,这是一个完整的示例:1. 我有以下元素 list :

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',
},
]
  1. 还有第二个项目列表:
const items = [
{
name: 'Fruits',
abbr: 'A',
},
{
name: 'Fruits1',
abbr: 'b',
},
]
  1. 我想将字符串“item.name”转换为“Fruits”,以便将常量 Fruits 作为列表传递给“newList”变量,如下所示:
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 将是第一个项目的“Fruits”,然后是第二个项目的“Fruits1”,依此类推...

最佳答案

如果我没理解错的话,您想使用项目的名称从 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 }
/>
);

关于javascript - 将来自变量的字符串转换为另一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821206/

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