如何将id数组与对象数组嵌套属性与下划线进行比较

时间:2016-05-04 11:17:59

标签: javascript arrays underscore.js

我正在使用一个不使用jquery的项目。我一直在使用下划线或香草javascript。这是我得到的东西。 plunker

// Code goes here
var successfullIdArray = ["713","281","555"];

var tmpTripsArry = [{
            "routeUUID": "123",
            "routeLocations": {
                "isSubmitLocationSuccess": false,
                "routeUUID": "123",
                "locationId": "713"
            }
        },{
            "routeUUID": "909",
            "routeLocations": {
                "isSubmitLocationSuccess": false,
                "routeUUID": "909",
                "locationId": "281"
            }
        },{
            "routeUUID": "800",
            "routeLocations": {
                "isSubmitLocationSuccess": false,
                "routeUUID": "800",
                "locationId": "555"
            }
        },{
            "routeUUID": "444",
            "routeLocations": {
                "isSubmitLocationSuccess": false,
                "routeUUID": "444",
                "locationId": "200"
            }
        }];    

 var tmpUpdatedTripsArry = _.each(tmpTripsArry, function () {
        _.find(tmpTripsArry, function (item) {
          if (successfullIdArray.locationId === item.routeLocations.locationId) {
               item.routeLocations.isSubmitLocationSuccess = true;
                   return item;
                } else {
                   return item;
                }
            });
        });        

        console.log(tmpUpdatedTripsArry)

我需要将locationId的tmpTripsArry嵌套属性与successfullIdArray进行比较,并使用

返回匹配的对象
  

isSubmitLocationSuccess

更改为true。

我没有得到任何错误,但它没有做我需要做的事情。谢谢。更喜欢使用下划线

1 个答案:

答案 0 :(得分:2)

简单地说是js

var matchingObjs = tmpTripsArry.filter( function(val){
  if ( successfullIdArray.indexOf( val.routeLocations.locationId ) != -1 )
  {
    val.routeLocations.isSubmitLocationSuccess = true;
  }
  return successfullIdArray.indexOf( val.routeLocations.locationId ) != -1 ;
}) 

如果您需要返回所有对象,请使用forEach

tmpTripsArry.forEach( function(val){
  if ( successfullIdArray.indexOf( val.routeLocations.locationId ) != -1 )
  {
    val.routeLocations.isSubmitLocationSuccess = true;
  }
}) 

现在tmpTripsArry本身具有修改后的值。