在while循环中将条目添加到JSON

时间:2019-06-23 07:02:27

标签: javascript json

如何在while循环中将键值对添加到JSON对象中?

var sName = "string_";
var aKeys = ["1", "2", "3"];
var sKey = "key";
var n = 1;
 var aObj = {};

var l = aKeys.length;
for(let i=0; i < l; i++){
   while(n < 5)
  {
    n += 1;
    aObj.sKey = sName.concat(n);
  }
}
console.log(JSON.stringify(aObj));

预期输出:

{"sKey":"string_2", "sKey":"string_3", "sKey":"string_4"}

1 个答案:

答案 0 :(得分:-1)

如前所述,Object不能有重复的密钥。 试试:

var value = "string_";
var sKey = "sKey_"
var i = 1;
var Obj = {};

while(i < 5)
{
  Obj[sKey.concat(i)] = value.concat(i++);
}

console.log(JSON.stringify(Obj));