从它的循环值

时间:2018-05-31 22:36:47

标签: javascript arrays

我创建了一个过滤器来从数组中检索对象。利用了一些对象值,但现在我想将id作为数组而不是单独使用。我知道在这种情况下推送是不对的,因为我仍然在过滤器内,我该如何实现呢?

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)
    }    
 })

1 个答案:

答案 0 :(得分:2)

您需要格式化数组。然后使用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);