本文介绍了JavaScript的由属性的对象数组删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的形式的阵列

  [
   {为prop1:值1,
   银行:[{_ ID:值,property2:值2}]
}]

所以,我想要做的是通过搜索_id值,删除银行性质的元素,然后从银行取出数组的元素找到

_ ID酒店唯一值,以便有什么价值不能多次出现

我喜欢

这样做

  $ scope.account.banks.splice($ scope.account.banks.indexOf(项目),1);

有这样做的更好的办法?


解决方案

您可以使用的删除匹配项目。它干净了一点比手动循环,虽然它仍然是一个有点冗长。我做了一个小测试案例来说明我在说什么。

\r
\r

VAR账户= {[\r
   为prop1:VALUE1,\r
   银行:[{_ ID:0,property2:sdfbra},\r
          {_id:1,property2:qwedfg},\r
          {_id:2,property2:gaasdf},\r
          {_id:3,property2:asdfaa'}]\r
}]\r
\r
VAR项目= {_id:1,property2:qwedfg'};\r
\r
账户[0] = .banks帐户[0] .banks.filter(函数(元素){\r
  返回element._id == item._id!;\r
});\r
\r
的console.log(帐户[0] .banks);

\r

\r
\r

I have an array of objects in the form of

[  
   {prop1: value1,
   banks:[{_id:value,property2:value2}]
}]

So what I want to do is delete an element in "banks" property by searching for the "_id" value and then remove the found element from the banks array

"_id" property has unique values so there are no multiple occurrences of any value

I am doing this like

$scope.account.banks.splice($scope.account.banks.indexOf(item),1);

is there any better way for doing this?

解决方案

You could use array.filter to remove the banks that match item. Its a little cleaner than manually looping though it's still a little verbose. I made a little test case to illustrate what I'm talking about.

var accounts = [{
   prop1: 'value1',
   banks:[{_id:0,property2:'sdfbra'},
          {_id:1,property2:'qwedfg'},
          {_id:2,property2:'gaasdf'},
          {_id:3,property2:'asdfaa'}]
}]

var item = {_id:1,property2:'qwedfg'};

accounts[0].banks = accounts[0].banks.filter(function(element){
  return element._id !== item._id;
});

console.log (accounts[0].banks);

这篇关于JavaScript的由属性的对象数组删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:27