简体   繁体   English

如何合并这两个JavaScript对象?

[英]How can I combine these two JavaScript objects?

I have two JavaScript objects as follows; 我有两个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"
      }
    ]
  }
]

I want to add the animals to the cages object, so that I end up with; 我想将动物添加到笼子对象中,以便最终实现;

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

What are some ways of combining two objects like this? 像这样组合两个对象的方法有哪些? Which ones are most efficient? 哪个效率最高? My first attempt had some nested for loops that got pretty deep and messy and never quite worked. 我的第一次尝试有一些嵌套的for循环,这些循环变得很深,很混乱,而且从未完全起作用。 Here's some incomplete logic I've got so far; 到目前为止,这里有一些不完整的逻辑;

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

I need to know how to specify which cage to push the animal into. 我需要知道如何指定将动物推入哪个笼中。 I wish it was as simple as cages[cage].push(animals[i]); 我希望它像cages[cage].push(animals[i]); but in this case the keys are the same for each cage object. 但在这种情况下,每个笼形对象的键都相同。

Using a nested loop 使用嵌套循环

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
            }
        );
    }
}

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

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