简体   繁体   中英

Is it possible to add values from array to object properties?

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"}

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.

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;
} 

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