将对象属性值分配给一个或多个变量

时间:2017-07-24 23:27:11

标签: javascript arrays object for-loop

我有这个对象:

{
  nameErr: "Name is required"
  numberErr: "Number is required"
  emailErr: "Email is required"
  genderErr: "Gender is required"
  messageErr: "Message is required"
}

这个数组:

var errorVars = [errorName, errorNumber, errorEmail, errorGender, errorMessage]

如何将属性nameErr的值分配给errorVars变量,并对数组中的其余变量执行相同的操作,是否可以?

类似的东西:

for(i=0; i<errorVars.length; i++){
  errorVars[i] = "property value[i]"
}

PS:使用纯JavaScript。

3 个答案:

答案 0 :(得分:2)

从上面的评论中您的问题是如何选择对象值,您可以使用obj.keyName选择它,或者如果动态键使用Object.keys(obj)

&#13;
&#13;
var obj = {
  nameErr: "Name is required",
  numberErr: "Number is required",
  emailErr: "Email is required",
  genderErr: "Gender is required",
  messageErr: "Message is required"
};
var errorVars = []
// select by key
console.log(obj.nameErr + "\n\n")

// for dynamic key
for(i = 0; i < Object.keys(obj).length; i++) {
  objValue = obj[Object.keys(obj)[i]];
  console.log(objValue)
  // convert to array
  errorVars.push(objValue)
}
console.log(errorVars)
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是使用vanilla JS将对象转换为数组的方法:

var ob = {
    nameErr: "Name is required",
    numberErr: "Number is required",
    emailErr: "Email is required",
    genderErr: "Gender is required",
    messageErr: "Message is required"
 }

var errorVars = [];

for(var i = 0 ; i < Object.keys(ob).length; i++) {
    var x = Object.keys(ob)[i]
    errorVars.push(x + " : " + ob[x]
};

console.log(errorVars);

答案 2 :(得分:0)

有可能。有两种选择: 1)你可以按相同的顺序制作它,所以

`var obj ={
nameErr: "Name is required"
//...
}
for(i=0; i<errorVars.length; i++){
  errorVars[i] = obj[i];
}`

2)您需要将errorVars结构稍微修改为

`var errorName ={
      name:"nameErr", value:""
};
var errorVars = [errorName];
for(i in errorVars) {
   errorVars[i].value = obj[errorVars[i].name];
}`