js数组间循环添加问题?

1.元数据
const arr1 = ["#355b54","#12d806","#748aac"];
const arr2 = [{type:"一类"},{type:"二类"},{type:"三类"},{type:"四类"},{type:"五类"},{type:"六类"},{type:"七类"},{type:"其他"}];

2.需要将arr中数据按照索引插入到arr2, arr1商量 继续从 arr[0] 添加.

3.最后的效果是这样:

const arr = [

{type:"一类",color:"#355b54"},
{type:"二类",color:"#12d806"},
{type:"三类",color:"#748aac"},
{type:"四类",color:"#355b54"},
{type:"五类",color:"#12d806"},
{type:"六类",color:"#748aac"},
{type:"七类",color:"#355b54"},
{type:"其他",color:"#12d806"}

]

阅读 3.3k
4 个回答
const arr = arr2.map((item, index) => ({
  ...item,
  color: arr1[index % arr1.length]
}))
const n = arr1.length;
arr2.forEach(
  function ( item, index ) {
    item.color = this[ index % n ];
  },
  arr1,
);

console.log( arr2 );
let arr1Length = arr1.length

let result = arr2.map((item, index) => {
    let idx = index % arr1Length // 取余,首尾循环
    return { ...item, color: arr1[idx] }
})

console.log(result)
arr = arr2.map((item, index) => (
  Object.assign(item,{color:arr1[index % arr1.length]})
))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题