1

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: [ commands :[] ] } Data.Info.push({'StateName': 'washington'}); Data.Info.commands.push( {'Type': 'Men'}, {'Parameter': '1000'}, ); $('.displayJsonBlock').empty(); $('.displayJsonBlock').append('<pre><code>' + JSON.stringify(TemplateData) + '</pre></code>') 

    2 Answers 2

    3

    If 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: [ commands :[] ] 

    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: { commands :[] } 

    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', commands: [] // each element of Info is an object with a commands array }); Data.Info[0].commands.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 commands:

    Data.Info.push({ 'StateName': 'washington', commands: [ {'Type': 'Men'}, {'Parameter': '1000'} ] }) 
      2

      Well, the structure of JSON data is incorrect, I think you do something like this

      var CountryName = 'UnitedStates'; var Data = { Name: CountryName, Info: [ {commands :[]} ] } 

      After

      Data.Info.push({'StateName': 'washington'}); Data.Info['commands'] = [{'Type': 'Men'}, {'Parameter': '1000'}]; 

      There is a good way, but I do not know if it is what you want.

      2
      • This will only get you one commands property on Data, whereas the desired JSON has a commands element on every element of Info.
        – Mark
        CommentedAug 8, 2018 at 23:55
      • Yes, I saw the structure after :/CommentedAug 9, 2018 at 0:03

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.