170

I have this JSON data:

{
    "employees": [
        {
            "firstName": "John",
            "lastName": "Doe"
        },
        {
            "firstName": "Anna",
            "lastName": "Smith"
        },
        {
            "firstName": "Peter",
            "lastName": "Jones"
        }
    ]
}

Suppose I don't know how many columns and rows of employees I have, how do I create this object in JavaScript (Without concate strings)? Assume that I get each row in "onGeneratedRow" method, and I need to push each column (firstName, lastName) to the '{}' brackets.

var viewData = { 
    employees : [] 
};

var rowNum = -1; 

function onGeneratedRow(columnsResult)
{
    rowNum = rowNum + 1;
    viewData.employees.push({});    
    columnsResult.forEach(function(column) {                  
    var columnName = column.metadata.colName;
    viewData.employees[rowNum][columnName] = column.value;  });
}
5
  • 2
    What is columnsResult? What is metadata? Commented May 12, 2013 at 12:14
  • 1
    This questions does not make sense to me at present, can you explain further, where is your data coming from and in what format. Are you just adding to existing data or creating all of it from scratch. Maybe you can create a jsfiddle to demonstrate what the problem you are having is.Is your question really just, how to access data within an array/ or javascript object? And lets be clear about the data, JSON or Javascript object: stackoverflow.com/questions/8294088/javascript-object-vs-json Commented May 12, 2013 at 12:20
  • 2
    assume "columnName" is "firstName" and "column.value" is the value (for example: "John"). I just need to know how to push them dynamically into the brackets ('{}') Commented May 12, 2013 at 12:24
  • 1
    What happens when you run the code you've shown? Commented May 12, 2013 at 12:34
  • @ohadinho it is unclear what is your input data strucuture (json) columnsResult Commented Apr 25, 2019 at 10:24

4 Answers 4

200

This is what you need!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }
Sign up to request clarification or add additional context in comments.

6 Comments

How did you know that the OP does not need to count the rows with ´rowNum´?
push does not need row number
because json generation does not need count, more you can always use .length to get rows.
I never said that JSON generation does. It was more the case that you state "This is what you need!", but I wanted to know how you knew that count was not needed by the OP, or did you just assume? Your answer does not generate JSON btw.
@WaqarAlamgir - that's exactly what I needed at this moment. Cheers!
|
137

Perhaps this information will help you.

var sitePersonel = {};
var employees = []
sitePersonel.employees = employees;
console.log(sitePersonel);

var firstName = "John";
var lastName = "Smith";
var employee = {
  "firstName": firstName,
  "lastName": lastName
}
sitePersonel.employees.push(employee);
console.log(sitePersonel);

var manager = "Jane Doe";
sitePersonel.employees[0].manager = manager;
console.log(sitePersonel);

console.log(JSON.stringify(sitePersonel));

Comments

22

This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:

valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray1[k];
    myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray2[k];
    myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));

The result in the console Log should be something like this:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}

2 Comments

Can I stress the usefulness in properly spacing the code you submit here? It's much harder to read without spacing.
This helped me out no end. Exactly what i required.
2

JavaScript

var myObj = {
   id: "c001",
   name: "Hello Test"
}

Result(JSON)

{
   "id": "c001",
   "name": "Hello Test"
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.