简体   繁体   中英

how to compare array of ids with object array nested property with underscore

I am working with a project that does not use jquery. I have been using underscore or vanilla javascript. Here is a plunker I have with what I got. 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)

I need to compare the tmpTripsArry nested property of locationId against the successfullIdArray and return the matching objects with the

isSubmitLocationSuccess

changed to true.

I am not getting any errors but it is not doing what I need it to do. thanks. prefer to use underscore

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

If you need all the objects to be returned, then use forEach instead

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

Now tmpTripsArry itself has the modified values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM