Home > Mobile >  How to create and empty JSON in JavaScript and add keys and additional JSON objects dynamically?
How to create and empty JSON in JavaScript and add keys and additional JSON objects dynamically?

Time:07-08

How to create and empty JSON in JavaScript and add keys and additional JSON objects dynamically?

mydata = {}

to

newdata = {
       'first': [ {'1': 'test'} ]
}

I tried this

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const myJSON = '{}';
myJSON['first']['1'] = 'test';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text  = x   ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

CodePudding user response:

Parse the json into an object, then set his properties

const myJSON = '{}';
const myObj = JSON.parse(myJSON);
myObj['first'] = [{'1':'test'}];

console.log(myObj);
newdata = {
       'first': [ {'1': 'test'} ]
}

CodePudding user response:

try this

var newData = { first: [{ 1: "test" }] };

//or 

const myJson = {};
myJson["first"]= [];
var newItem={ "1": "test" };
myJson["first"].push(newItem);
myJson["second"]= [];
newItem={ "2": "test" };
myJson["second"].push(newItem);

console.log(JSON.stringify(myJson));
  • Related