javascript迭代数组并根据条件执行操作

时间:2018-04-17 05:28:52

标签: javascript arrays if-statement

我在localstorage中有以下数组

[  
   {  
      "customerId":"30",
      "CustomerContactId":63873
   },
   {  
      "customerId":"26506",
      "CustomerContactId":63874
   },
   {  
      "customerId":"26596",
      "CustomerContactId":63875
   },
   {  
      "customerId":"26597",
      "CustomerContactId":63876
   }
]

我们从下拉列表中选择客户的功能。在select customer上,我将customerId传递给该函数。在函数中,我调用api为该customerId生成CustomerContactId。 我想迭代这个数组,并想检查customerId是否存在于数组中,然后不执行生成CustomerContactId API,但如果整个数组中不存在customerId,则为该customerId创建CustomerContactId。 我试过javascript地图功能。这里this.state.customerContactMap = localstorage数组。 cust_id =选定的客户。

this.state.customerContactMap.map(item => {
   if(item.customerId === cust_id) {
     //Do not generate new CustomerContactId
   } else {
     //Generate CustomerContactId API Call
     //it should only generate CustomerContactId if cust_id is not 
     //exist in array
   }
})

但我遇到的问题是它每次进入else条件时都会创建CustomerContactId。我需要条件逻辑方面的帮助。

4 个答案:

答案 0 :(得分:1)

您可以使用array#some检查数组中是否存在customerId

const customerContactMap = [{ "customerId": "30", "CustomerContactId": 63873 }, { "customerId": "26506", "CustomerContactId": 63874 }, { "customerId": "26596", "CustomerContactId": 63875 }, { "customerId": "26597", "CustomerContactId": 63876 }],
      custId = 30;
if(customerContactMap.some(({customerId}) => customerId == custId)){
  console.log('found');
} else {
  //Execute API
}

答案 1 :(得分:0)

只有这种情况:

 if(item.customerId === cust_id) {

似乎item.customerId的类型和cust_id的类型不同。

尝试转换:

 if(item.customerId == cust_id) {

OR

 if(item.customerId === cust_id.toString()) {

答案 2 :(得分:0)

您应该使用.some()代替.map()

根据Docs

  

some()方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。

例如:

if(arr.some(({ customerId }) => customerId === selectedId))
  console.log("Selected Found");
else
  console.log("Selected Not Found");

<强>演示:

let arr = [{ "customerId": "30", "CustomerContactId": 63873}, {"customerId": "26506","CustomerContactId": 63874}, {"customerId": "26596","CustomerContactId": 63875}, {"customerId": "26597","CustomerContactId": 63876}];

let selectedId = "26596";

if(arr.some(({ customerId }) => customerId === selectedId))
  console.log("Selected Found");
else
  console.log("Selected Not Found");

答案 3 :(得分:0)

您可以使用Array.filter检查客户ID是否存在。

&#13;
&#13;
var data = [{
"customerId": "30",
"CustomerContactId": 63873
}, {
"customerId": "26506",
"CustomerContactId": 63874
}, {
"customerId": "26596",
"CustomerContactId": 63875
}, {
"customerId": "26597",
"CustomerContactId": 63876
}]

function getCustomer(id){
  return data.filter(function(e){
    if(e.customerId == id){
      return true;
    }
  });
}

var custId = getCustomer("26597");

if(custId.length == 0){
  console.log("Not exists");
  //network call
}else{
  console.log("Exists");
  console.log(custId);
  //normal operations of cust id available
}
&#13;
&#13;
&#13;