简体   繁体   English

Map 通过 js/react 中的对象数组

[英]Map through an array of objects in js/react

I need an array of alt strings.我需要一个alt字符串数组。 I can map the array with name strings, but can't get it to return the "alt".我可以用name字符串 map 数组,但不能让它返回“alt”。 This is what I tried:这是我尝试过的:

const data = [
  { name: "Apple", alt: "Fruit" },
  { name: "Banana", alt: "Fruit" },
  { name: "Potatoe", alt: "Vegetable" },
  { name: "Lentil", alt: "Legume" }];
  <span>
      {data.map(item => {
        return (
         <Button item={item.alt.toUpperCase()}>
         {item}
         </Button>
         );
       })}
  </span>

To get an array of name strings, this worked:要获取name字符串数组,这有效:

  <span>
      {data.map(item => {
        return (
         <Button key={item.name} item={item.name.toUpperCase()}>
         {item}
         </Button>
         );
       })}
  </span>

This is the error: TypeError: Cannot read property 'toUpperCase' of undefined这是错误:TypeError:无法读取未定义的属性“toUpperCase”

I think you are trying to create a button please look below我认为您正在尝试创建一个按钮,请看下面

The below code is modified to use key in map function as each of your record is unique and react keys are useful when working with dynamically created components or when your data are altered.下面的代码被修改为使用 map function 中的键,因为您的每条记录都是唯一的,并且在使用动态创建的组件或更改数据时,反应键很有用。 Setting the key value will keep your components uniquely identified after the change and they also help in performance.You can read the below blog it explains well about using keys.设置键值将使您的组件在更改后保持唯一标识,它们也有助于提高性能。您可以阅读下面的博客,它很好地解释了使用键。 https://programmingwithmosh.com/react/why-do-i-need-keys-in-react-lists/ https://programmingwithmosh.com/react/why-do-i-need-keys-in-react-lists/

 const data = [
      {id:1, name: "Apple", alt: "Fruit" },
      {id:2 ,name: "Banana", alt: "Fruit" },
      {id:3, name: "Potatoe", alt: "Vegetable" },
      {id:4, name: "Lentil", alt: "Legume" }
    ];
    function App() {
      return (
        <span>
          {data.map((item) => (
            <button key={item.id}>{item.alt.toUpperCase()}</button>
          ))}
        </span>
      );
    }

Use this link it is working here https://codesandbox.io/s/friendly-wave-t117u使用此链接它在这里工作https://codesandbox.io/s/friendly-wave-t117u

Give this a try:试试这个:

<span>{
  data.map(
    (item, index) => <button 
      alt={item.alt.toUpperCase()} 
      key={someKeyHere}>
        {item.alt.toUpperCase()}
      </button>)
}</span>

Here's a Working Sample StackBlitz for your ref.这是您参考的 工作示例 StackBlitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM