简体   繁体   English

如何从数组中删除对象并保存以供以后使用?

[英]How to remove object from Array and save it for use later?

Originally my question was How to Remove Object from jQuery array . 最初我的问题是如何从jQuery数组中删除对象 < Found the answer, the one from @nnnnnn. <找到答案,来自@nnnnnn的答案。 Using $.grep 使用$.grep

My new question now is how would you save the object that you just removed? 现在,我的新问题是如何保存刚刚删除的对象?

Reason is I wish to be able to push that saved Object back into the Array if the user decides to keep it. 原因是,如果用户决定保留它,我希望能够将保存的对象推回到数组中。

My networks array: 我的networks数组:

console: 安慰:
networks array = [object Object],[object Object]

networks: Array[2]
    0: Object
      count: 1
      id: "6"
      label: "CompanyName"
      type: "Organization"

    1: Object
      count: 1
      id: "12622"
      label: "MyGroup"
      type: "Group"

From the other answer I'm using this to look in the networks array, find the Object with the type of "Organization" and remove it. 从另一个答案中,我正在用它来查找网络数组,找到类型为“组织”对象并将其删除。

networks = $.grep(networks, function(o,i) { return o.type === "Organization"; }, true);

Is there a simple way to save that entire Object? 是否有保存整个对象的简单方法? So it can be pushed back in? 这样可以推回去吗?

Thanks for taking a look! 谢谢参观!

You could assign the object inside the callback to a variable. 您可以将回调内的对象分配给变量。 This isn't a very clean solution, since such callbacks shouldn't have side effects IMO, but it works without making bigger changes to your code: 这不是一个很干净的解决方案,因为此类回调不应该给IMO带来副作用,但是它可以在不对代码进行较大更改的情况下起作用:

var obj;
networks = $.grep(networks, function(o,i) {
  if (o.type === "Organization") {
      obj = o;
      return true;
  }
  return false;
}, true);

or a bit shorter (and more confusing for people who don't know about the comma operator): 或短一些(对于不了解逗号运算符的人更加困惑):

var obj;
networks = $.grep(networks, function(o,i) { 
    return o.type === "Organization" ? ((obj = o), true) : false;
}, true);

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

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