[英]I have two array, one have N no of data and and another have fixed no of data
我有兩個數組,一個有 n 個數據,第二個數組有固定的數據數,其中包括 5-6 種顏色
例子 :
數組 1 =>
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 =>
const bgColor = ['red', 'pink', 'blue', 'green'];
我想合並 2 個數組,意味着我想將背景顏色添加到第一個數組(類別),當第二個數組元素完成時,它再次以索引 0 開始
我想要像這樣的數組:
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"
},
.
.
.
.
.
.
];
要獲得循環索引,您可以使用余數運算符 (%) ,其中最大索引是顏色數組的長度:
categories.map((category, index) => {
const circularIndex = index % bgColors.length
return {...category, color: bgColors[circularIndex] }
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.