按值从数组拼接行

时间:2016-11-16 12:03:16

标签: javascript jquery

我想拼接值= 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);

    }

}

结果

只有拼接或仅循环此代码才有效。

但是,两者都显示了这个错误:

  

未捕获的TypeError:无法读取未定义(...)

的属性“0”

它出现在“data.rows [i] [0]”

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

只需在条件中添加break,因为下一个元素就是您拼接的元素,而不再是数组。

if (del == id) {  // if del = id -> splice
   data.rows.splice(i, 1);
   break; // no more to search
}

答案 2 :(得分: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));

答案 3 :(得分:0)

您可以使用lodash来过滤对象或数组。根据您的情况查看filter method

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;
});