1

Is it possible to map values from array to javascript object?

Let's say that we have array like this

var cars = ["Saab", "Volvo", "BMW"];

and an object

let someObject = {
SAAB: null,
VOLVO: null,
BMW: null
}

And I want to map values from array to object to output it like this:

let someObject = {
    SAAB: "Saab",
    VOLVO: "Volvo",
    BMW: "BMW"
    }

I tried something along this lines but failed miserably

for (let key of Object.entries(someObject)) {
  for (let index = 0; index < cars.length; index++) {
    key = cars[index];
  }
}

Also, I tried this solution but somehow I missed something and it mapped only last value

for (var key in someObject) {
  for (var car in cars) {
    someObject[key] = cars[car]
  }
}
console.log(someObject)

{SAAB: "BMW", VOLVO: "BMW", BMW: "BMW"}
Svinjica
  • 1,761
  • 29
  • 50

2 Answers2

3

If the relationship is the order you could use for in and shift()

var cars = ["Saab", "Volvo", "BMW"];

let someObject = {
SAAB: null,
VOLVO: null,
BMW: null
}


for(let p in someObject){
    someObject[p] = cars.shift()
}

console.log(someObject)

Order in a For in loop is not guaranteed by ECMAScript specification, but see this, either way order probably is not the best way to relation things.

Emeeus
  • 4,104
  • 2
  • 14
  • 32
1

If you want to map even though the relationship between the two objects might not be the order you can something like this:

for(let car of cars){
someObject[car.toUpperCase()] = car;
}

Which eventually fixes any missing values in the object. Also you can add a check so that only pre-existing values in the object get their value assigned:

for(let car of cars){
if(someObject[car.toUpperCase()])
    someObject[car.toUpperCase()] = car;
} 
Gigi
  • 149
  • 7