0

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.* e.g. 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

  • 1
    Wait. What are you exactly trying to do here? – briosheje Apr 08 '19 at 12:28
  • The first argument of `apply` is the context, you can also access it as a static property. It doesn't make sense – Christian Vincenzo Traina Apr 08 '19 at 12:29
  • `ajaxResult[i].selectedTripLeader = $scope.TripLeaderData[0].Id`? – adiga Apr 08 '19 at 12:29
  • Sounds like you're trying to [add a new property to each object](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) in your array. – James Apr 08 '19 at 12:30
  • Possible duplicate of [Add property to an array of objects](https://stackoverflow.com/questions/38922998/add-property-to-an-array-of-objects) – adiga Apr 08 '19 at 12:31
  • The code is from the last solution i have tried, I want key-value pair at each item of the ajaxResult array. But I'm not able to push directly into ajaxResult[item]. It displaying error 'Push is not a function' – Bhavin patel Apr 08 '19 at 12:32
  • ajaxResult[i].selectedTripLeader = $scope.TripLeaderData[0].Id I'm using this to display dropdown list for each row. i.e. to assign andular model – Bhavin patel Apr 08 '19 at 12:34
  • Please add which array you are getting from API and your $scope.TripLeaderData in question – Hrishi Apr 08 '19 at 13:49

2 Answers2

0

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
-1

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
      };
    }
  }
Giu Magnani
  • 448
  • 1
  • 3
  • 12