Create JSON from jQuery each loop

javascript, jquery, json

Solution

Welcome to Stackoverflow. You did not write any error messages you got, so I assume the following.

// 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;
});

EDIT

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}}

Problem

All the questions I have dug through in the boards aren't really answering a question I have. So I will ask the experts here. First off, thank you very much for reading on. I really appreciate what Stackoverflow is all about, hopefully I can contribute now that I am a member. I want to dynamically create a JSON object based off variables set from another JSON object from with a jQuery each loop. I think my syntax and probably my knowledge of this stuff is a little off. I would like to end up with the following JSON structure: ``` { desktop:{ title:300, rev:200 } } ``` Where "desktop" is a value from another JSON object not in this loop, I can call that no problem, in fact it is actually the name value I set on the other JSON object. I am looping through an array in the object called columns but want to set a separate object containing all the widths because the columns are adjustable and accessible via another frame that I will push it to, I want to retain those widths. I was trying to do this from within the loop: ``` var colWidths = {}; $.each(columns, function(i) { colWidths.desktop.title = columns[i].width; }); ``` I can alert columns[i].width successfully. The issue I have is creating and accessing this. Everything I seem to be doing seems right but this is not the case. Maybe its me or my setup? Could you please show me how to code this properly? OR I could create a Javascript Object if this is not possible. Thanks in advance!

Original source