-4

How to add key value pair into an JSON object in a while loop?

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

expected output:

{"sKey":"string_2", "sKey":"string_3", "sKey":"string_4"}
Dali
  • 1
  • 3
  • expected output: {"sKey":"string_2", "sKey":"string_3", "sKey":"string_4"} – Dali Jun 23 '19 at 07:02
  • 1
    You can't have keys with duplicate names. – Herohtar Jun 23 '19 at 07:04
  • this is not possible to have the same key for every value. and btw, you are overwriting `String`. – Nina Scholz Jun 23 '19 at 07:05
  • You can't have same key more than once in a single object. – Mohammad Usman Jun 23 '19 at 07:06
  • Hi Dali. Welcome to SO. Your expected output is not a valid JSON, each key in a JSON object needs to be unique. If you want a key to hold multiple values, then it is preferable that it be an array e.g. `{"sKey": ["string_2", "string_3", "string_4"]}` – Bhavin Jun 23 '19 at 07:07
  • thanx, my real key will be a iterated one, and my value will be a Set. I just wanted to simplify example. How do I add the entry pair to a JSON without incremented [i] like in a for loop? – Dali Jun 23 '19 at 07:15
  • You're saying that the value will be a Set. What will be the key? – Mosh Feu Jun 23 '19 at 07:17
  • in my real script it will be a new Set() , and the keys will be new Strings, or if equals will not be added as new key. – Dali Jun 23 '19 at 07:28
  • If you're not actually expecting there to be duplicate keys then you need to show the correct output that you are expecting instead of the invalid one you listed. – Herohtar Jun 23 '19 at 07:34
  • sorry about not being accurate. When i use a new Map() and set the entries I get the right result. But how to with a JSON? – Dali Jun 23 '19 at 07:36

1 Answers1

-1

As mentioned, Object can't have duplicate keys. Try:

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));
Ziv Ben-Or
  • 1,149
  • 6
  • 15