当我从angualrjs中的数组中删除数组对象项时如何更新Array对象索引?

时间:2017-01-28 09:37:35

标签: javascript angularjs

这是我的数组对象

var item = [
    {index:1, name: 'miraje'},
    {index:2, name: 'alamin'},
    {index:3, name: 'behestee'},
    {index:4, name: 'arif'},
    {index:5, name: 'riad'}
];

当我删除像index:2这样的对象时,我想更新我的索引值,如..

   var item = [
            { index: 1, name: 'miraje'},
            { index: 2, name: 'behestee'},
            { index: 3, name: 'arif'},
            { index: 4, name: 'riad'}
         ];

4 个答案:

答案 0 :(得分:0)

删除元素后,您可以使用forEach()循环来更改索引。

var item = [
{index:1, name: 'miraje'},
{index:2, name: 'alamin'},
{index:3, name: 'behestee'},
{index:4, name: 'arif'},
{index:5, name: 'riad'}
];

item.splice(1, 1)
item.forEach((e, i) => e.index = i + 1)
console.log(item)

答案 1 :(得分:0)

删除对象并更改每个对象的索引属性

<强>样本

i=1;
var item = [
{index:1, name: 'miraje'},
{index:2, name: 'alamin'},
{index:3, name: 'behestee'},
{index:4, name: 'arif'},
{index:5, name: 'riad'}
];
console.log(item);
delete item[ 2 ];
console.log(item);
item.forEach(function(obj) {
     obj.index = i;
     debugger;
     i++;
});
console.log(item);

答案 2 :(得分:0)

基本上,您需要找到包含index的项目,将其删除,并更新以下所有项目。

function deleteItem(array, index) {
    var i = 0, found = false;
    while (i < array.length) {
        if (found) {
            --array[i].index;
            ++i;
            continue;
        }
        if (found = array[i].index === index) {
            array.splice(i, 1);
            continue;
        }
        ++i;
    }
}

var items = [{ index: 1, name: 'miraje' }, { index: 2, name: 'alamin' }, { index: 3, name: 'behestee' }, { index: 4, name: 'arif' }, { index: 5, name: 'riad' }];

deleteItem(items, 2);
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

仅针对多种类型,在不修改原始阵列的情况下,有效的O(n)方法也将如下。我们还可以提供一个范围来删除元素......

提供的范围是数组索引,而不是对象索引属性。

&#13;
&#13;
var item = [
    {index:1, name: 'miraje'},
    {index:2, name: 'alamin'},
    {index:3, name: 'behestee'},
    {index:4, name: 'arif'},
    {index:5, name: 'riad'}
];
function deleteObjectsFromArray(a,j,k){
  return a.reduceRight((p,c,i) => i >= j && i < k ? p
                                                  : i >= k ? (c.index -= k-j, p[c.index-1] = c, p)
                                                           : (p[c.index-1] = c, p),[]);
}

console.log(deleteObjectsFromArray(item,2,4));
&#13;
&#13;
&#13;