Create JSON from jQuery of each loop

All the questions that I burst on the boards do not really answer the question that I have. Therefore, I will ask experts here. First of all, many thanks for reading. I really appreciate what Stackoverflow is, hope now I can contribute to being a member.

I want to dynamically create a JSON object based on variables set from another JSON object using jQuery of each loop. I think that my syntax and probably my knowledge of this material does not work a bit.

I would like to get the following JSON structure:

{
  desktop:{
    title:300,
    rev:200
  }
}

If the “desktop” is the value of another JSON object not in this loop, I can call it a problem, in fact it is actually the value of the name that I set on another JSON object. I iterate over the array in an object called columns, but I want to set up a separate object containing all the widths, because the columns are customizable and accessible through another frame, which I click on, I want to save these widths.

I tried to do this from a loop:

var colWidths = {};
$.each(columns, function(i) {
    colWidths.desktop.title = columns[i].width;
});

I can warn the columns of [i] .width successfully. The problem I am creating is to create and access this. Everything that I seem to do seems right, but it is not. Maybe it's me or my installation? Could you show me how to encode this correctly? Or I could create a Javascript object if that is not possible. Thanks in advance!

+5
1

Stackoverflow. , .

// prepare the object correctly first
var colWidths = {
   desktop: {
      title: 0
   }
};
// then ADDING each value with += instead of = 
// (because in your code you will just have the last value)
$.each(columns, function(i) {
    colWidths.desktop.title += columns[i].width;
});

var grid = {
    "name": "desktop",
    "columns": [
        {
        "id": "icons",
        "width": 50},
    {
        "id": "title",
        "width": 200},
    {
        "id": "name",
        "width": 300},
    {
        "id": "revision",
        "width": 400}
    ]
};

var columns = grid.columns;
var gridName = grid.name;

var colWidths = {};

// CHANGE HERE
colWidths[gridName] = {}; 

$.each(columns, function(c) {

   var col = columns[c];
   var colname = col.id;
   var colwidth = col.width;

   // CHANGE HERE
   var thisGrid = colWidths[gridName];
   if(!thisGrid[colname]) thisGrid[colname] = 0;

   thisGrid[colname] += colwidth;

});

//alert(colWidths.desktop.title);​
document.write(JSON.stringify(colWidths));

// RESULT:
// {"desktop":{"icons":50,"title":200,"name":300,"revision":400}}
+3

All Articles