简体   繁体   中英

How to add attribute to the root of JSON object consists of array of objects?

How to add attribute to the root of JSON object consists of array of objects?

If my JSON object something like that:

 [
   {
      "Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
      "Name":"W",
      "NumberOfWorkHours":8,
      "NumberOfShortDays":1,
      "WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
   },
   {
      "Id":"5c267601-fcf2-4735-9e49-b4def3981648",
      "Name":"S",
      "NumberOfWorkHours":6,
      "NumberOfShortDays":0,
      "WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
   }
]

I do the following:

worktimeJSON.Id = $('.Js-WorkTime-id').val();
worktimeJSON.Name = $('.Js-WorkTime-name').val();
worktimeJSON.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();

And make sure that the jQuery fetching data from the inputs but this doesn't work.

This will change property of all object in array if you want to change in particular then use index for this for exp->

worktimeJSON[0].Id = $('.Js-WorkTime-id').val();
worktimeJSON[0].Name = $('.Js-WorkTime-name').val();
worktimeJSON[0].NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();

 var worktimeJSON = [ { "Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9", "Name":"W", "NumberOfWorkHours":8, "NumberOfShortDays":1, "WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99" }, { "Id":"5c267601-fcf2-4735-9e49-b4def3981648", "Name":"S", "NumberOfWorkHours":6, "NumberOfShortDays":0, "WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580" } ]; worktimeJSON = worktimeJSON.map(function(val){ val.Id = $('.Js-WorkTime-id').val(); val.Name = $('.Js-WorkTime-name').val(); val.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val(); return val; }); 

Push can do the job.

 let worktimeJSON = [ { "Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9", "Name":"W", "NumberOfWorkHours":8, "NumberOfShortDays":1, "WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99" }, { "Id":"5c267601-fcf2-4735-9e49-b4def3981648", "Name":"S", "NumberOfWorkHours":6, "NumberOfShortDays":0, "WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580" } ]; worktimeJSON.push ({ id: "someID", name: "toto", WorkTimeRegulationId: 42 }); console.log(worktimeJSON); 

I structure my object like this:


 let WorkTimeRegulationViewModelJSON = {
                Id: $('.Js-WorkTimeRegulation-id').val(),
                Name: $('.Js-WorkTimeRegulation-name').val(),
                NumberOfAvailableRotations: $('.Js-WorkTimeRegulation-rotations').val(),
                AssignedWorkTimes: JSON.parse(worktimeJSON)

            };

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM