简体   繁体   English

从对象数组中的数组中选取Component的值

[英]Pick values to Component from array within array of objects

The user has own list of tags and each item owned by the user can have multiple tags from this tag list. 用户具有自己的标签列表,并且用户拥有的每个项目都可以从该标签列表中包含多个标签。

Here I am trying to map all the users tags for one item and if the specific item has a tag from the userTag list then those tag Chip element should have a different style aqua coloured background. 在这里,我尝试映射一个项目的所有用户标签,如果特定项目具有userTag列表中的标签,则这些标签Chip元素应具有不同的样式浅绿色背景。

I am struggling on finding a way to get the 'tag: array' values and implementing the Chip element style accordingly to multiple tags. 我正在努力寻找一种获取“标签:数组”值的方法,并相应地对多个标签实施Chip元素样式。 Here I can only get the item.tag array for the first tag item.tag[0]. 在这里,我只能获取第一个标签item.tag [0]的item.tag数组。 How would I go by when trying to get each value from the nested tag array inside itemsData and give the item multiple aqua coloured tags if it has multiple tags. 尝试从itemsData内的嵌套标签数组获取每个值并为该项目提供多个浅绿色标签(如果它具有多个标签)时,我将如何处理。

例

 const itemsData = [
 { id: 1, tag: ['Fysik', 'Matematik'] },
 { id: 2, tag: ['Analytics', 'Marketing', 'Data'] },
 { id: 3, tag: [''] },
 ];
<div>
  {userTags.map(tag => (
    <Chip
      label={tag}
      variant={item.tag[0] === tag ? 'default' : 'outlined'}
      onClick={() => { onTagSelected(tag, item.id); }}
    />
  ))}
</div>

You could use Array.indexOf to determine whether it is in the item's tag array or not. 您可以使用Array.indexOf来确定它是否在项目的标签数组中。

<div>
  {userTags.map(tag => (
    <Chip
      label={tag}
      variant={item.tag.indexOf(tag) > -1 ? 'default' : 'outlined'}
      onClick={() => { onTagSelected(tag, item.id); }}
    />
  ))}
</div>

You could check if some of the items tags includes the tag: 您可以检查某些项目标签是否包含标签:

 itemsData.some(item => item.tag.includes(tag))

If you do that check more often on a large dataset it might be benefitial to build up a Set, then lookup is O(1): 如果您在大型数据集上更频繁地进行检查,则建立一个Set可能是有益的,则查找值为O(1):

 // Build up the Set once
 const highlightedTags = new Set(itemsData.flatMap(item => item.tag));

 // Then lookup:
 highlightedTags.has(tag)

Try this: 尝试这个:

 <div>
      {userTags.map(tag => (
        <Chip
          label={tag}
          variant={item.tag.includes(tag) ? 'default' : 'outlined'}
          onClick={() => { onTagSelected(tag, item.id); }}
        />
      ))}
    </div>

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

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