简体   繁体   English

是否可以将值从数组添加到对象属性?

[英]Is it possible to add values from array to object properties?

Is it possible to map values from array to javascript object? 是否可以将值从数组映射到javascript对象?

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() 如果关系是可以for inshift()的顺序

 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. ECMAScript规范不能保证For in循环中的顺序,但是请看 ,两种方式中的顺序可能都不是联系事物的最佳方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM