开发者

remove entry from javascript array object

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"}];

开发者_Go百科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..


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 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])

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

Hope this helps.


Just use the del keyword:

delete arr["key"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜