我有一个对象数组。然后我想添加另一个对象并将其粘贴到我的数组中已经存在的对象中。这意味着新对象的索引应该比我已经存在的对象大1,并且元素索引的其余部分应该加1。
例如:
我尝试将我的数组拆分为两个,从index = 2开始,推送我的新元素,然后再次加入,但我的代码运行不正常。
for (var i in myArray) {
if (myArray[i].name === inheritedRate.inherit) {
var tempArr = [];
for (var n = i; n < myArray.length; n++) {
tempArr.push($scope.myArray[n]);
myArray.splice(n, 1);
}
myArray.push(inheritedRate);
myArray.concat(tempArr);
}
}
换句话说,我有一个看起来像这样的数组:
myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]
我想在那里添加一个外部元素来使它看起来像这样:
myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "new element"}, // inserted
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]
答案 0 :(得分:4)
如果我理解正确,那么问题就在于如何在数组中插入和移动元素。您可以使用splice方法执行此操作,该方法具有要插入的元素的可选参数:
以下是您的示例所需的内容:
var myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},
{name: "not selected"},
{name: "not selected"}
];
myArray.splice(3, 0, {
name: "new element"
});
console.log(myArray);
答案 1 :(得分:2)
您可以使用Array#splice
并在元素插入数组后获取索引。
var array = [{ name: "not selected" }, { name: "not selected" }, { name: "selected" }, { name: "not selected" }, { name: "not selected" }, { name: "not selected" }],
index = 2,
item = { name: "new element" };
array.splice(index + 1, 0, item);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }