关于常用的数组遍历问题

1.js匹配数组中对应的值_匹配字符串跟数组中存在相同值,并取出数组中的对应元素,转载自博主 https://blog.csdn.net/weixin_39548490/article/details/111758328
栗子如下:
字符串strA 和数组arrB,要找出arrB中id符合strA的值,并生成一个新的数组

在这里插入代码片
let strA = "1,2,3,4,5"
let arrB = [{
"id": "2",
"name": "小王"
},
{
"id": "5",
"name": "小明"
},
{
"id": "8",
"name": "小红"
},
{
"id": "11",
"name": "小点"
},
{
"id": "15",
"name": "小赵"
},
{
"id": "22",
"name": "小小"
}]

let obj = {}
for(let i in arrB){
obj[arrB[i].id] = arrB[i];
}

let strArr = strA.split(',');
let newArr = [];
for(let item of strArr){
if(obj[item]){
newArr.push(obj[item]);
}
}
console.log(newArr)

————————————————
版权声明:本文为CSDN博主「weixin_39548490」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39548490/article/details/111758328

2.两个长度相同数组,分别对应为key,value 生成新数组

在这里插入代码片
  let arrCode = []
  let arrDesc = []
  this.settingResource.budgetCoupon.map(item => {
      this.form.gainCoupon.push(item.code)
      arrCode.push(item.code)
      arrDesc.push(item.desc)
  })
  
  for(let i=0; i<arrCode.length; i++){
      let obj = {}
      for (let j = 0; j < arrDesc.length; j++) {
          if (i === j) {
              obj.code = arrCode[i]
              obj.desc = arrDesc[j]
              this.budgetForm.budgetArr.push(obj)
          }
      }
  }

3.更改数组对象中的属性名称

在这里插入代码片
const list = [{
    id: 'a',
    title: 'A'
}, {
    id: 'b',
    title: 'B',
    children: [{
        id: 'c',
        title: 'C'
    }, {
        id: 'd',
        title: 'D'
    }]
}]

let res = list.map(item=>{return {name:item.title,code:item.id}})
————————————————
版权声明:本文为CSDN博主「syx_12」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/syx_12/article/details/119853067
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值