【问题标题】:How can I combine these two JavaScript objects?如何组合这两个 JavaScript 对象?
【发布时间】:2014-07-31 16:30:14
【问题描述】:

我有两个 JavaScript 对象如下;

cages = [
  {
    "id":1,
    "name":"Cage 1"
  },
  {
    "id":2,
    "name":"Cage 2"
  }
]

animals = [
  {
    "id":1,
    "name":"doge",
    "cages": [
      {
        "id":1,
        "name":"Cage 1"
      },
      {
        "id":2,
        "name":"Cage 2"
      }
    ]
  }
  {
    "id":2,
    "name":"kat",
    "cages": [
      {
        "id":2,
        "name":"Cage 2"
      }
    ]
  }
]

我想将动物添加到笼子对象中,这样我就得到了;

cages = [
  {
    "id":1,
    "name":"Cage 1",
    "animals": [
      {
        "id":1,
        "name":"doge"
      }
    ]
  },
  {
    "id":2,
    "name":"Cage 2",
    "animals": [
      {
        "id":1,
        "name":"doge"
      },
      {
        "id":2,
        "name":"kat"
      }
    ]
  }
]

像这样组合两个对象有哪些方法?哪些效率最高?我的第一次尝试有一些嵌套的 for 循环,这些循环变得非常深沉和混乱,而且从来没有完全奏效。到目前为止,这是我所掌握的一些不完整的逻辑;

for(var i=0; i<animals.length; i++) {
    for(var n=0; n<animals.cages.length) {
      cages[].push(animals[i]);
    }
  }

我需要知道如何指定将动物推入哪个笼子。我希望它像cages[cage].push(animals[i]); 一样简单,但在这种情况下,每个笼子对象的键都是相同的。

【问题讨论】:

  • 使用例如迭代animals i,嵌套在其中,迭代 animals[i].cages,例如j,您现在应该拥有构建数据所需的所有信息。此外,要遍历 Array,您只需使用普通的 for,因为您可以访问 .length 并且所有内容都使用索引,for..in 用于通用 Objects 其中键/属性名称可以是任何 String
  • @PaulS。使用for each(animal in animals)for (var i = 0; i &lt; animals.length; i++) 本质上是一样的,但我仍然不确定如何选择cages 数组中的哪个对象将动物推入。
  • for each..in is depreciated,在 ES6 中类似的东西是 for..of,但你仍然不应该将其中任何一个用于 Array。你不能假设Array.prototype 中没有可枚举的东西,例如如果由于某种原因您需要在将来为某些东西添加 shim 或 polyfill Array.prototype.contains = function contains(x) {return this.indexOf(x) !== -1};,那么您现在也将迭代该函数
  • @PaulS。我在示例中更改了 for each 循环。但我的问题还是一样。
  • 我认为我需要弄清楚的是; 'cages 数组中的哪个索引包含一个对象,其键“id”的值为 x。'

标签: javascript arrays object merge


【解决方案1】:

使用嵌套循环

var i, j, k;
for (i = 0; i < animals.length; ++i) {
    for (j = 0; j < animals[i].cages.length; ++j) {
        // assuming cages[k].id === k
        // you may want to create a new cages object instead
        k = animals[i].cages[j].id; // neat shorthand
        if (!cages[k].animals) { // if no animals yet
            cages[k].animals = []; // initialise
        }
        cages[k].animals.push(
            { // add new animal to cage
                id: animals[i].id,
                name: animals[i].name
            }
        );
    }
}

【讨论】:

  • 假设cages[k].id === k 部分是我卡住的地方,因为在这种情况下不是这样。我将如何创建一个新的笼子对象?
  • 每个 id 都是唯一的吗?你最好使用 Objects 而不是 Arrays
  • 这是一个对象数组。我坚持使用我所拥有的,因为原始对象来自 api 响应。每个 ID 都是唯一的。
  • 我正在考虑是否可以使用 underscore.js 来简化此操作。
猜你喜欢
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
相关资源
最近更新 更多