![](/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.