首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我有两个数组,一个有N个数据,另一个有固定的数据

我有两个数组,一个有N个数据,另一个有固定的数据
EN

Stack Overflow用户
提问于 2021-10-13 07:12:55
回答 1查看 34关注 0票数 0

我有两个数组,一个包含n个数据,第二个包含固定数量的数据,其中包含5-6种颜色

示例:

阵列1 =>

代码语言:javascript
复制
const category = [
{
  name: 'Groceries',
  icon: ICONS.GROCERY,
},
{
  name: 'Bakery',
  icon: ICONS.BAKERY,
},
{
  name: 'General Stores',
  icon: ICONS.GENERAL_STORE,
},
{
  name: 'Cafe & Food',
  icon: ICONS.CAFE,
},
{
  name: 'Apparels',
  icon: ICONS.APPARELS,
},

 .
 .
 .
 .
 .
 .

];

阵列2 =>

代码语言:javascript
复制
 const bgColor = ['red', 'pink', 'blue', 'green'];

我想合并2个数组,这意味着我想在第一个数组(类别)中添加背景色,当第二个数组元素再次以索引0开始时

我想要像这样的数组:

代码语言:javascript
复制
const category = [
{
  name: 'Groceries',
  icon: ICONS.GROCERY,
  color:"red"
},
{
  name: 'Bakery',
  icon: ICONS.BAKERY,
  color:"pink"
},
{
  name: 'General Stores',
  icon: ICONS.GENERAL_STORE,
  color:"blue"
},
{
  name: 'Cafe & Food',
  icon: ICONS.CAFE,
  color:"green"
},
{
  name: 'Cafe & Food',
  icon: ICONS.CAFE,
  color:"red"
},
{
  name: 'Apparels',
  icon: ICONS.APPARELS,
  color:"pink"
},

 .
 .
 .
 .
 .
 .

];
EN

回答 1

Stack Overflow用户

发布于 2021-10-13 07:19:44

要获得循环索引,您可以使用remainder operator (%),其中max index是颜色数组的长度:

代码语言:javascript
复制
categories.map((category, index) => {
  const circularIndex = index % bgColors.length
  return {...category, color: bgColors[circularIndex] }
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69551154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档