needed some help, so I have a json in this format
{
"objs": {
"block": [
{"long": "value1"}
],
"block1": [
{"long": "value2"}
],
"nameofblock": [
{"long": "thisisthevalueoflonginjson"}
]
}
}
Now I need to add a new array using js, I am not allowed to change the structure of the JSON so now, in my js I have something like this
let myBlock = "name_of_block";
let longData = "data_inside_the_block";
Now using these variables a new block needs to be created in the existing JS file using the variables in JS
so once these are added the JSON must look something like this
{
"objs": {
"block": [
{"long": "value1"}
],
"block1": [
{"long": "value2"}
],
"nameofblock": [
{"long": "thisisthevalueoflonginjson"}
],
"name_of_block": [
{"long": "data_inside_the_block"}
]
}
}
Thanks for reading, I have tried in Discord, but still couldn't figure it out
Something as simple as this should do the trick:
myJSON.objs[myBlock] = [{"long": longData}];
Where myJSON
is the object you want to attach it to.
See the example below:
const myJSON = { "objs": { "block": [ {"long": "value1"} ], "block1": [ {"long": "value2"} ], "nameofblock": [ {"long": "thisisthevalueoflonginjson"} ] } }; let myBlock = "name_of_block"; let longData = "data_inside_the_block"; myJSON.objs[myBlock] = [{"long": longData}]; console.log(myJSON);
JSON structure is same with JS Object.
so you can do it like below.
function createBlock = (longData) => [{"long":longData}];
jsonObj.objs[myBlock] = createBlock(longData);
let x ={
"objs": {
"block": [
{"long": "value1"}
],
"block1": [
{"long": "value2"}
],
"nameofblock": [
{"long": "thisisthevalueoflonginjson"}
],
"name_of_block": [
{"long": "data_inside_the_block"}
]
}
}
x.objs.newProperty= 'New value'
console.log(x) --->
{
objs: {
block: [ [Object] ],
block1: [ [Object] ],
nameofblock: [ [Object] ],
name_of_block: [ [Object] ],
newProperty: 'new Value'
}
}
``
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.