简体   繁体   中英

Push element at each index in an array

I have an array, i wan to add one more key value pair at each index.

var ajaxResult = ajaxGet("URL");
    if (ajaxResult.length > 0) {
        for (var i = 0; i < ajaxResult.length; i++) {
            debugger

            ajaxResult[i].prototype.push.apply({ "selectedTripLeader": $scope.TripLeaderData[0].Id });
            debugger
        }
    }

I am trying to achieving * selectedTripLeader at each array item present into ajaxResult.* eg array[0].push({ "selectedTripLeader": $scope.TripLeaderData[0].Id }) array[1].push({ "selectedTripLeader": $scope.TripLeaderData[0].Id })

i have tried using normal push and prototype.push but it is not working. Solution with for loop or for each loop will be ok

At an index of i in ajaxResult, its an object(ajaxResult[i]). You can't use push function on an object, you can use it on an array. To append a new key-value pair inside an existing object, you can do the following thing:

var a={}; a.name='Joe'; OR a[name]='Joe';

Both are the ways to add new key-value pair in Object.

So in your scenario, it should be as below given code.

 ajaxResult[i].selectedTripLeader= $scope.TripLeaderData[0].Id
                          OR
 ajaxResult[i]['selectedTripLeader'] = $scope.TripLeaderData[0].Id

If you want to add a property to your object, you can use the spread operator to merge the current object with your new property:

var ajaxResult = ajaxGet("URL");
  if (ajaxResult.length > 0) {
    for (var i = 0; i < ajaxResult.length; i++) {
      ajaxResult[i] = {
        ...ajaxResult[i],
        selectedTripLeader: $scope.TripLeaderData[0].Id
      };
    }
  }

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