Concatenate object to array without merging JavaScript JS

Viewed 44

I am currently struggling with this problem. I've been through numerous forums and websites and didn't get the answer. I would like to concatenate two objets in one array without merging using this car object constructor, :

const car = {
  year: '',
  model: '',
  mileage: '',
  available_colors: [1, 2, 3], // numbers indicate color id
};

var garage = [];

const honda = Object.create(car);
const volvo = Object.create(car);

honda.available_colors[1] = 34;
volvo.available_colors[0] = 80;
honda.year = 1987;
volvo.year = 1990;
garage.push(honda, volvo);

console.log(garage);

Problem is, here is the result i have :

    console.log(garage[0].available_colors,garage[1].available_colors);
    -->[80,2,3] , [80,2,3]
 
    console.log(garage[0].year, garage[1].year);
    -->1987 , 1990

The problem doesn't appear for the other parameters, only the array. How can i have two separate available_colors arrays that belong to each object separately?

2 Answers

honda.available_colors and volvo.available_colors refer to the same Array object.

You can instead make a new array for each car, using a slice'd copy of car.available_colors as a starting point for each:

honda.available_colors = honda.available_colors.slice();
honda.available_colors[1]=34;
volvo.available_colors = volvo.available_colors.slice();
volvo.available_colors[0]=80;

This will make a new array instance for each car instance, so they don't share the same array. Note that this means future changes to the prototype value car.available_colors will not be visible to instances after they're created: each instance will copy the state of the prototype's available_colors at creation time.

You need to make a shallow copy of both the car object and available_colors array

I used Object.assign and the spread operator

You can read about Object.assign and the spread operator here and here

const car= {
    year:'',
    model:'',
    mileage:'',
    available_colors:[1,2,3], // numbers indicate color id
}

var garage =[];

const honda = Object.assign({}, car);
const volvo = Object.assign({}, car);

honda.available_colors = [...honda.available_colors];
honda.available_colors[1] = 34;
volvo.available_colors= [...volvo.available_colors];
volvo.available_colors[0] = 80;
honda.year = 1987;
volvo.year = 1990;
garage.push(honda, volvo);

console.log(garage);

Related