Swarnadeep
Swarnadeep

Reputation: 341

bind in json format from two different arrays in jquery

I want to bind the json data I got from Site into following json format:

{
  "siteList": [
    {
      "siteName": "Site1",
      "deviceList": [
        {
          "deviceName": "S1device1"
        },
        {
          "deviceName": "S1device2"
        }
      ]
    },
    {
      "siteName": "Site2",
      "deviceList": [
        {
          "deviceName": "S2device1"
        },
        {
          "deviceName": "S2device2"
        }
      ]
    }
  ]
}

I have stored the site name and device name in two different array please help me bind me bind all of this into the format given above.

The jQuery code I used to store the data:

$(document).ready(function() {
     $("input:checkbox[name=check]:checked").each(function(){
      
    var id=$(this).attr('id');
    var site_data = $(this).closest('tr').find('#site').val();
    var device_data = $(this).closest('tr').find('#device').val();
    site_checks.push(site_data);
    device_checks.push(device_data);
});
  var site_check_length = site_checks.length;
 var device_check_length = device_checks.length;
  var site_data_list = [];
     for(var site = 0 ; site < site_check_length ; site++){
        var sites_checked = {};
        var device_checked = {};
        sites_checked['siteName'] = site_checks[site];
        sites_checked['deviceName'] = device_checks[site];
        site_data_list.push(sites_checked);
      }
      console.log(site_data_list);
          });

});
(2) [{…}, {…}]
0: {siteName: "Site1", deviceName: "S1device1"}
1: {siteName: "Site2", deviceName: "S2device1"}

length: 2 This sort of ouput is coming but i have to bind it in above given json format Help!!!

Upvotes: 0

Views: 95

Answers (1)

Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2645

In the success function you have provided, you could parse the data accordingly. Here is an example of how you can do so. JSON.stringify will create a JSON string for you using an array of data.

let siteList = [];
let siteListItem = [];
siteListItem.siteName = "Site1";
siteListItem.deviceList = [];

// Create new device
let device_details = [];
device_details.deviceName = 'S1Device';  
// Push device to deviceList
siteListItem.deviceList.push(device_details);

// Push new site to siteList
siteList.push(siteListItem);

// Create a JSON String out of all the changes we've made
console.log(JSON.stringify(siteList));

Though this may seem like a suitable solution, its generally better to find an API provided by the site owner, or to create your own to parse the data on the back-end via PHP, Python or whatever language you are using.

This will ensure you can modify data across multiple clients without having to adjust the local code everytime you want to restructure the JSON string.

Upvotes: 1

Related Questions