从javascript数组对象中删除条目 [英] remove entry from javascript array object

查看:98
本文介绍了从javascript数组对象中删除条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Js中有两个对象数组

I have two object array in Js

a = [{"photoId":"1","albumId":"121"},{"photoId":"2","albumId":"131"},{"photoId":"3","albumId":"131"}] ;
b = [{"photoId":"2","albumId":"131"}];

我想从一个对象数组中删除b对象数组。所以输出应该是

I want to remove b object array entry from the a object array..so the output should be

c = [{"photoId":"1","albumId":"121"},{"photoId":"3","albumId":"131"}];

在数组的情况下很容易实现,但如何对数组对象做同样的事情..

its easy to achieve in case of array but how to do the same for array object..

推荐答案

看起来像对象数组更难,但实际上与'普通数组'相同。只需检查其内容。您应该循环数组以检查对象是否相同。然后像这样使用Array.slice():

It looks like an object array is more difficult, but is actually the same as a 'normal array'. Just check on its content. You should loop trough the array to check if the objects are the same. Then use the Array.slice() like this:

for (var i = a.length - 1; i >= 0; i--) //always use a reversed loop if you're going to remove something from a loop
{
  if (a[i].photoId == b[0].photoId &&
      a[i].albumId == b[0].albumId) // if the content is the same
  {
     a.splice(i, 1); // remove the item from 'a'
  }
}

BTW delete-statement使数组中的项为空,splice将其完全删除,因此数组的长度变小。

BTW the delete-statement makes the item in the array empty, splice removes it completely, so the length of the array becomes smaller.

注意;如果您正在处理同一对象的引用,则可以使用以下条件:

Note; If you are dealing with references of the same object, you could use this condition:

if (a[i] == b[0])

当然,如果'b'中有更多项目,你也会有建立一个双循环。

Ofcourse, if there are more items in 'b', you'll have too build a double loop.

希望这有帮助。

这篇关于从javascript数组对象中删除条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆