Create JSON object dynamically via JavaScript (Without concate strings)

前端 未结 4 1180
傲寒
傲寒 2020-11-30 18:05

I have this JSON data:

{
    \"employees\": [
        {
            \"firstName\": \"John\",
            \"lastName\": \"Doe\"
        },
        {
                  


        
相关标签:
4条回答
  • 2020-11-30 18:26

    JavaScript

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

    Result(JSON)

    {
       "id": "c001",
       "name": "Hello Test"
    }
    
    0 讨论(0)
  • 2020-11-30 18:34

    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);
     }
    
    0 讨论(0)
  • 2020-11-30 18:38

    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
      }
    }
    
    0 讨论(0)
  • 2020-11-30 18:43

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

    0 讨论(0)
提交回复
热议问题