Search code examples
javascriptarraysjavascript-objects

Merging Two Objects Into Array While Keeping Key Values


How can I combine two objects into an array while also keeping the key values within the objects? I've found solutions to merging objects but none of them seem to keep the key values.

My code is creating new cars. I want to organize my new cars into an array while later, being able to organize them by model, model year, color, etc. Some of that organizational logic has not been implemented yet as I'm focusing on getting the object merging ironed out before the data becomes too long.

class Car {
    constructor(type, model_year) {
        this.type = type,
        this.model_year = model_year

    }
}

class Tesla extends Car{
    constructor(type, model_year){

        super(type, model_year)
    }
}

let myTesla1 = new Tesla("Sedan", 2015)
let myTesla2 = new Tesla("Coupe", 2014)

My desired output would be:

let teslas = // Here is what I'm failing to implement
console.log(teslas)
// ["type", "Sedan", "model_year", "2015", "type", "Coupe", "model_year", "2014"]

Maybe my logic wrong here. I'm sure there is a better way to organize these cars but I'm failing to figure that out as well.

My Attempt

I attempted to map over the object using entries like so:

let teslas = Object.entries(myTesla1).map(([key, value]) => ({key, value}));
console.log(teslas);

But my output wasn't exactly what I was looking for as it put the key values like so:

[ { key: 'type', value: 'Sedan' },
  { key: 'model_year', value: 2015 } ]

Thanks in advance for any help. I'm fairly new to this so please excuse anything that should be done a better way.


Solution

  • I'm going to work with your comment: I'm sure there is a better way to organize these cars but I'm failing to figure that out as well

    I'm going to suggest that what you want is an array with one entry per car, and that entry is a simple map of the key-value pairs. You can use Object.assign to accomplish the mapping from your class instances to a plain object:

    class Car {
      constructor(type, model_year) {
        this.type = type,
        this.model_year = model_year
      }
    }
    
    class Tesla extends Car {
      constructor(type, model_year) {
        super(type, model_year)
      }
    }
    
    let myTesla1 = new Tesla("Sedan", 2015)
    let myTesla2 = new Tesla("Coupe", 2014)
    
    const teslas = [myTesla1, myTesla2]
    
    const carListWithKeyValues = teslas.map(tesla => Object.assign(tesla))
    
    console.log(carListWithKeyValues)
    
    /*
    output:
    
    [
      {
        "type": "Sedan",
        "model_year": 2015
      },
      {
        "type": "Coupe",
        "model_year": 2014
      }
    ]
    
    */