Home > front end >  JS: Add objects form an array to objects inside another array
JS: Add objects form an array to objects inside another array

Time:11-18

DISCLAIMER: Please dont mind my stupid object names, its just to learn the basics

I have an array of objects named "cars":

const cars = [
  {
    name: "red",
    competes: true,
    category: 2,
    given: 400
  },
  {
   name: "blue",
   competes: false,
   category: 2,
    given: 0
  },
  {
    name: "green",
    competes: true,
     category: 2,
    given: 0
  }
]

And another array of objects named addOns:

const addOns = [
  {
    name: "hyperblast",
    upgrade: 100
  },
  {
    name: "catalyst",
    upgrade: 400
  }
]

Question

How can i add for example the addOn {name: "catalyst", upgrade: 400} to the car named "green"?
Ive tried with

cars[2].push(addOns[1]);

but it doesnt work. And all my google searches were without result (arrays of objects seem so important but I constantly fail to find anything regarding. Only about arrays or objects, never together)

CodePudding user response:

You could add the addOns as another field of the car object. For your example: cars[2].extra = addOns[0]; . After typing this, if you try to console the cars[2] you will see:

{
  name: 'green',
  competes: true,
  category: 2,
  given: 0,
  extra: { name: 'hyperblast', upgrade: 100 }
}

Since you are working with vanilla Js, the cars[0].extra is going to work, but if you use TS in future, it would be better to define a field before adding it, or changing the structure of the script completely

CodePudding user response:

As cars and addOns both have the property key 'name', I would change the second one to 'addOnName' or something of that sort. Otherwise, 'green' will just be overwritten to 'hyperblast' in the result.

Being that you're trying to add multiple properties to an object, you should use a for...in loop. As you can see below, I've cycled through the cars array with a regular for loop. If the given car's name is 'green' I call the addProps function and pass it the given car object as an argument. Each prop in your chosen addOns object is then added on to the given car obj.

const addProps = (obj) => {
  for (let prop in addOns[0]) {
    obj[prop] = addOns[0][prop];
  }
}

for (let i = 0; i < cars.length; i  ) {
  if (cars[i].name === 'green') {
    addProps(cars[i]);
  }
}

console.log(cars);
  • Related