如何使用表单数据在javascript中创建嵌套的对象数组?

时间:2017-03-30 06:04:34

标签: javascript

我是javascript的新手,请帮我解决这个问题。 我有一组json格式的数据,现在我想使用表单数据插入另一条记录作为对象。 以下是样本数据 -

dummydata=[{
    property1: "John",
    property2:[
                {id:[1]},
                {IsRequired:[]}
              ],
    property3: [
      "text1",
      "text2"
    ],
    property4:[
        {
        orderId:1,
        text:"Hello",
        cardType:"",
        options: ""
        },
        {
        orderId:3,
        text:"Hello World",
        cardType:[],
        options: [ 
            {Id:1},
            {Id:2}
             ]
        }
    ]
  }
  {...
  ..}
  ]

以下是我的controller.js -

    //Javascript constructor
    function record(property1, property2, property3, property4){

  this.property1 = property1;
  this.property2 = (function(id, isrequired)
                    {
                        this.id=id;
                        this.isrequired=isrequired;
                    });
  this.property3 = property3;
  this.property4 = (function(orderId, text, cardType, options)
                    {
                        this.orderId=orderId;
                        this.text=text;
                        this.cardType=cardType;
                        this.options=options;
                    });
 }

function addRecord()
{
    var property1Input=document.forms["intent_form"]["property1"].value;
    var property2Input=document.forms["intent_form"]["property2"].value;
    var property3Input= document.forms["intent_form"]["property3"].value;
    var property4Input= document.forms["intent_form"]["property4"].value;

    var newDataSet = JSON.parse( localStorage.getItem('key_newDataSet' ) );
    var newRecord = new record(property1Input,property2Input, property3Input,property4Input);
        newDataSet.push(newRecord );
        localStorage.setItem("key_newDataSet", JSON.stringify(newDataSet));
}

我真的很无能为力,因为如何构建整个记录并将其推送到现有记录中。提前谢谢。

1 个答案:

答案 0 :(得分:0)

根据您的示例代码,我认为您需要更新addRecord(),您需要从构造函数对象中推送新数据:

    function addRecord(dummydata)
    {
        var property1Input=document.forms["intent_form"]["property1"].value;
        var property2Input=document.forms["intent_form"]["property2"].value;
        var property3Input= document.forms["intent_form"]["property3"].value;
        var property4Input= document.forms["intent_form"]["property4"].value;

        var newDataSet = JSON.parse( localStorage.getItem('key_newDataSet' ) );
        var newRecord = new record(property1Input,property2Input, property3Input,property4Input);

        // Create a new json object here
        var objToBeInsert = {
        property1:newRecord.property1,
        property2:newRecord.property2,
        property3:newRecord.property3,
        property4:newRecord.property4
        };

        //Now push this object to your list.
        newDataSet.push(objToBeInsert);
        localStorage.setItem("key_newDataSet", JSON.stringify(newDataSet));
    }

注意:如果对您有帮助,请标记此答案。