按值从数组中删除行

5

我想要将值为3的行拼接起来

[3,"John", 90909090]

data.json

{
"headers":[[
{"text":"Code","class":"Code"},
{"text":"Code","class":"Code"}
]],
"rows":[
[0,"Peter", 51123123],
[3,"John", 90909090],
[5,"Mary",51123123]
],
"config":[[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],
"other":[[13,0]]
}

我尝试了这个:

var size = data.rows.length; // number of rows

var del = 3 // Value of ID to be deleted          

for (i = 0; i < size; i++) {  

var id = data.rows[i][0];                  

    if(del==id){  // if del = id -> splice                                         

       data.rows.splice(i,1);

    }

}

结果:

只使用splice或仅使用循环,此代码可以正常工作。

但是,两者一起使用会显示以下错误:

Uncaught TypeError: Cannot read property '0' of undefined(…)

它出现在"data.rows[i][0]"处。


1
这是一个很好的过早微优化浪费时间的例子。没有必要使用那个 size 变量;直接与 data.rows.length 进行比较即可。如果你这样做了,就不会遇到这个错误。(你也将继续处理更多的条目。是否要这样做取决于数组中是否可能出现多个 3...) - T.J. Crowder
真相。 \o/ 谢谢。 - Gurigraphics
4个回答

3

不使用for循环,而是使用数组的过滤函数:

data.rows = data.rows.filter(function(row){
    return row[0] !== del;
});

2
只需在条件语句中添加一个break,因为下一个元素是你已经切割的元素,不再存在于数组中。
if (del == id) {  // if del = id -> splice
   data.rows.splice(i, 1);
   break; // no more to search
}

1
值得解释一下为什么会出现错误(size的缓存)。 - T.J. Crowder

1
您可以使用Array#forEach()进行迭代:

var data = {"headers": [[{"text": "Code","class": "Code"}, {"text": "Code","class": "Code"}]],"rows": [[0, "Peter", 51123123],[3, "John", 90909090],[5, "Mary", 51123123]],"config": [[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],"other": [[13, 0]]},
    del = 3; // Value of ID to be deleted

data.rows.forEach(function(item, index) {
  item[0] === del && data.rows.splice(index, 1);
});

console.log(data.rows);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6:

data.rows.forEach((item, index) => item[0] === del && data.rows.splice(index, 1));

0

你可以使用lodash来过滤你的对象或数组。针对你的情况,可以查看filter方法

var myObject = {
"headers":[[
{"text":"Code","class":"Code"},
{"text":"Code","class":"Code"}
]],
"rows":[
[0,"Peter", 51123123],
[3,"John", 90909090],
[5,"Mary",51123123]
],
"config":[[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],
"other":[[13,0]]
};

//filter by lodash
myObject.rows =  _.filter(myObject.rows,function(row){
  return row[0] !== 3;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接