javascript - 从循环值创建一个数组

标签 javascript arrays

我创建了一个过滤器来从数组中检索对象。使用了一些对象值,但现在我想将 ids 作为数组而不是单独使用。我知道在这种情况下推送是不正确的,并且由于我仍在过滤器内,请问我该如何实现这一点?

arrayList = [
  {
     id: 48589,
     height: 5.8,
     active: false
  },
  {
     id: 84697,
     height: 4.6,
     active: true
  },
 {
     id: 887697,
     height: 5.0,
     active: true
   }
 ]

 arrayList.filter(c => {
    if(c.active){
     //`I used the other values here
    } else {
    //Now I need c.id as an array to search my db

       ids = [];
       ids.push(c.id)
    }    
 })

最佳答案

您需要格式化您的数组。然后使用map()从现有数组创建一个新数组:

var arrayList = [
  {
     id: 48589,
     height: 5.8
  },
  {
     id: 84697,
     height: 4.6
  }
]

 var ids = arrayList.map(c => c.id);
 console.log(ids);

根据问题中的更新,您可以尝试 forEach() 并且您还在外部声明了 ids:

var arrayList = [
  {
     id: 48589,
     height: 5.8,
     active: false
  },
  {
     id: 84697,
     height: 4.6,
     active: true
  },
 {
     id: 887697,
     height: 5.0,
     active: true
   }
]
var ids = [];
arrayList.forEach(c => {
  if(c.active){
   //`I used the other values here
  } else {
  //Now I need c.id as an array to search my db
     ids.push(c.id)
  }    
});
console.log(ids);

关于javascript - 从循环值创建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633737/

相关文章:

android - 数组字符串声明

java - 方法中的数组

c 字符串数组比较

javascript - 为什么这么多 Array.prototype(迭代)方法这么慢?

java - 如何使用 HashMap 将多个值放入 ArrayList?

javascript - 如何在 VSCode 中快速切换 block 和表达式样式的箭头函数

php - 替换单引号和双引号

javascript - 如果选中则禁用表单

javascript - 修改传入_each回调参数的对象

javascript - 如何动态插入可能包含链接和脚本标签的html?