![](/img/trans.png)
[英]Javascript how to push a new element from an initial array to each array inside an array of arrays at the same index?
[英]Push element at each index in an array
我有一个数组,我想在每个索引处再添加一个键值对。
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
}
}
我正在尝试在存在于ajaxResult。*中的每个数组项上实现* selectedTripLeader。*例如array [0] .push({“ selectedTripLeader”:$ scope.TripLeaderData [0] .Id})array [1] .push({ “:$ scope.TripLeaderData [0] .Id})
我已经尝试使用普通的push和prototype.push,但是无法正常工作。 for循环或每个循环的解决方案都可以
在ajaxResult的i索引处,它是一个对象(ajaxResult [i])。 您不能在对象上使用推功能,而可以在数组上使用它。 要将新的键值对附加到现有对象中,您可以执行以下操作:
var a = {}; a.name ='乔'; 或a [name] ='Joe';
两种方法都是在Object中添加新的键值对的方法。
因此,在您的情况下,它应该如下所示。
ajaxResult[i].selectedTripLeader= $scope.TripLeaderData[0].Id
OR
ajaxResult[i]['selectedTripLeader'] = $scope.TripLeaderData[0].Id
如果要向对象添加属性,则可以使用传播运算符将当前对象与新属性合并:
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.