I am trying to get a json object like the below
{
"Name":"UnitedStates",
"Info":[
{"StateName":"Washington",
"Commands":[
{"Type":"Men","Parameter":"10000"},
{"Type":"Women","Parameter":"30000"}
]},
{"StateName":"California",
"Commands":[
{"Type":"Kids","Parameter":"20000"}
]}
]}
I am trying the below Fiddle
How can I add array of values to existing blank object.
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [
mands :[]
]
}
Data.Info.push({'StateName': 'washington'});
Data.Infomands.push(
{'Type': 'Men'},
{'Parameter': '1000'},
);
$('.displayJsonBlock').empty();
$('.displayJsonBlock').append('<pre><code>' + JSON.stringify(TemplateData) + '</pre></code>')
I am trying to get a json object like the below
{
"Name":"UnitedStates",
"Info":[
{"StateName":"Washington",
"Commands":[
{"Type":"Men","Parameter":"10000"},
{"Type":"Women","Parameter":"30000"}
]},
{"StateName":"California",
"Commands":[
{"Type":"Kids","Parameter":"20000"}
]}
]}
I am trying the below Fiddle
How can I add array of values to existing blank object.
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [
mands :[]
]
}
Data.Info.push({'StateName': 'washington'});
Data.Info.mands.push(
{'Type': 'Men'},
{'Parameter': '1000'},
);
$('.displayJsonBlock').empty();
$('.displayJsonBlock').append('<pre><code>' + JSON.stringify(TemplateData) + '</pre></code>')
Share
Improve this question
asked Aug 8, 2018 at 23:36
KurkulaKurkula
6,78228 gold badges137 silver badges215 bronze badges
2 Answers
Reset to default 3If you look at the error console output, you'll see it's giving you a syntax error because Info
is trying to be both an object and an array at the same time:
Info: [
mands :[]
]
If you want to push into Info
it needs to be an array, but that means you can't define properties in the literal like this. If you want to define properties like this it needs to be a an object like:
Info: {
mands :[]
}
But then you can't push.
I think what you're looking for is:
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [] // info is just an array
}
Data.Info.push({
'StateName': 'washington',
mands: [] // each element of Info is an object with a mands array
});
Data.Info[0].mands.push( // you need to define which element of info. Here it's the first
{'Type': 'Men'},
{'Parameter': '1000'},
);
console.log(Data)
Of course you don't need to do two pushes you can push the whole object including mands
:
Data.Info.push({
'StateName': 'washington',
mands: [
{'Type': 'Men'},
{'Parameter': '1000'}
]
})
Well, the structure of JSON data is incorrect, I think you do something like this
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [
{mands :[]}
]
}
After
Data.Info.push({'StateName': 'washington'});
Data.Info['mands'] = [{'Type': 'Men'}, {'Parameter': '1000'}];
There is a good way, but I do not know if it is what you want.