[英]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 }) 我正在尝试在存在于ajaxResult。*中的每个数组项上实现* selectedTripLeader。*例如array [0] .push({“ selectedTripLeader”:$ scope.TripLeaderData [0] .Id})array [1] .push({ “:$ scope.TripLeaderData [0] .Id})
i have tried using normal push and prototype.push but it is not working. 我已经尝试使用普通的push和prototype.push,但是无法正常工作。 Solution with for loop or for each loop will be ok
for循环或每个循环的解决方案都可以
At an index of i in ajaxResult, its an object(ajaxResult[i]). 在ajaxResult的i索引处,它是一个对象(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={}; var a = {}; a.name='Joe';
a.name ='乔'; OR a[name]='Joe';
或a [name] ='Joe';
Both are the ways to add new key-value pair in Object. 两种方法都是在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
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.