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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

True, it's correct. We only need to declare p variable otherwise we get reference error. Like this: for (let p in someObject) { someObject[p] = cars.shift() }
In this case, it's the same, but it's better declare p
what about not sorted array?
@аlexdykyі we need some relation. I guess in this case the order, but could be the strings or other thing.
@Emeeus it's not a answer, please fix your code or remove answer
|
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;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.