简体   繁体   English

JQUERY-使用键从多维数组中删除数组

[英]JQUERY - remove array from a multidimensional array with key

I am trying to remove an array in a multidimensional array if the id is the same off the given one. 我试图删除多维数组中的数组,如果id与给定的ID相同。

var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}];

var result = test_arr.filter(function(v,i) {  
     if (v[0] === '123456'){ test_arr.splice(i,1) } 
}); 

//alert( test_arr[0].id)
alert(result)

http://jsfiddle.net/ofLg0vq5/2/ http://jsfiddle.net/ofLg0vq5/2/

How Could I do this? 我该怎么办?

The issue with your current solution is that you're not using .filter correctly. 当前解决方案的问题是您没有正确使用.filter .filter expects its passed function to return a boolean . .filter期望其传递的函数返回boolean If true is returned, the current element will be kept in the newly generated array. 如果返回true ,则当前元素将保留在新生成的数组中。 If it is false , the current element will be omitted. 如果为false ,则将省略当前元素。 So, instead of trying to remove the element from test_arr using .splice , use .filter to decide what stays and what gets removed. 因此, test_arr使用.splice尝试从test_arr删除元素, test_arr使用.filter来决定保留哪些内容以及删除哪些内容。

Also, note that in your example v is referring to a given element (a particular object) in your test_array . 另外,请注意,在示例中, v引用了test_array的给定元素(特定对象)。 Thus, you do not need to target index 0 of your object, but rather you need to get the id of the current object. 因此,您不需要以对象的索引0为目标,而是需要获取当前对象的id

 var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}]; test_arr = test_arr.filter(function(elem) { return elem.id !== '123456'; }); console.log(test_arr); // [{"name": "ggg", "city": "uk", "id": "777456"}] 

If you want a "cleaner" solution you can use an arrow function with destructing assignment : 如果您需要“更清洁”的解决方案,则可以使用具有破坏性分配 功能箭头功能

test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}]

 var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}]; test_arr = test_arr.filter(({id}) => id !== '123456'); // [{"name": "ggg", "city": "uk", "id": "777456"}] console.log(test_arr); 

@Nick had given solution without .splice , but If for any reason you still want to go for .splice solution, you can try below code. @Nick给出了不带.splice解决方案,但是如果出于任何原因仍然想使用.splice解决方案,则可以尝试以下代码。

You are were checking id in wrong way, in below solution it will remove all objects with id - 123456 您正在以错误的方式检查id ,在以下解决方案中,它将删除所有id -123456的对象

http://jsfiddle.net/u0qshcvf/2/ http://jsfiddle.net/u0qshcvf/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM