简体   繁体   中英

How can I combine these two JavaScript objects?

I have two JavaScript objects as follows;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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