marlsun 2022-09-02 09:05 采纳率: 84.2%
浏览 44
已结题

根据已有属性值往对象数组中添加相应的新属性

问题: 随机生成颜色数组arr4,根据arr5的value值,依次添加相应的color属性值。(实际需处理的数组中的value值类型较多)


const arr1 = ["red","blue","yellow","green","pink"]

const arr2 = [
  {name: "tom", value: 1},
  {name: "tom", value: 1},
  {name: "tom", value: 2},
  {name: "tom", value: 5},
  {name: "tom", value: 2},
  {name: "tom", value: 1},
  {name: "tom", value: 3},
  {name: "tom", value: 3},
  {name: "tom", value: 1},
  {name: "tom", value: 4},
  {name: "tom", value: 3},
  {name: "tom", value: 4},
  {name: "tom", value: 5},
  {name: "tom", value: 4},
]

const arr3 = [
  {name: "tom", value: 1,color: "red"},
  {name: "tom", value: 1,color: "red"},
  {name: "tom", value: 2,color: "blue"},
  {name: "tom", value: 5,color: "pink"},
  {name: "tom", value: 2,color: "blue"},
  {name: "tom", value: 1,color: "red"},
  {name: "tom", value: 3,color: "yellow"},
  {name: "tom", value: 3,color: "yellow"},
  {name: "tom", value: 1,color: "red"},
  {name: "tom", value: 4,color: "green"},
  {name: "tom", value: 3,color: "yellow"},
  {name: "tom", value: 4,color: "green"},
  {name: "tom", value: 5,color: "pink"},
  {name: "tom", value: 4,color: "green"},
]

谢谢!

  • 写回答

4条回答 默认 最新

  • Z_pigeon 2022-09-02 09:13
    关注
    
    const arr1 = ["red", "blue", "yellow", "green", "pink"]
    
    const arr2 = [
        { name: "tom", value: 1 },
        { name: "tom", value: 1 },
        { name: "tom", value: 2 },
        { name: "tom", value: 5 },
        { name: "tom", value: 2 },
        { name: "tom", value: 1 },
        { name: "tom", value: 3 },
        { name: "tom", value: 3 },
        { name: "tom", value: 1 },
        { name: "tom", value: 4 },
        { name: "tom", value: 3 },
        { name: "tom", value: 4 },
        { name: "tom", value: 5 },
        { name: "tom", value: 4 },
    ]
    
    const arr3 = arr2.map((i, index) => ({ ...i, color: arr1[i.value - 1] }))
    console.log('arr3', arr3)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 9月10日
  • 已采纳回答 9月2日
  • 创建了问题 9月2日

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi