JSON array pushing

前端 未结 2 2032
萌比男神i
萌比男神i 2020-12-09 22:09

I have this example array for an entry to be inserted to a YUI datatable

var book = {
        \"id\" : \"po-0167\",
        \"date\" : new Date(1980, 2, 24),         


        
相关标签:
2条回答
  • 2020-12-09 22:49
    var book = {
            "id" : "po-0167",
            "date" : new Date(1980, 2, 24),
            "quantity" : 1,
            "amount" : 4,
            "title" : "A Book About Nothing"
        };  
    

    it's not array.
    Array is

    var books =[{
       "id" : "po-0167",
       "date" : new Date(1980, 2, 24),
       "quantity" : 1,
       "amount" : 4,
       "title" : "A Book About Nothing"
    }]  
    

    and after manipulation in your example you will get next array

    var book2 =[{
       "id" : "po-0167"
    },{
       "date" : new Date(1980, 2, 24)
       },{
       "quantity" : 1
    },{
       "amount" : 4
    },{
       "title" : "A Book About Nothing"
    }]  
    

    it's not the same.
    You must do next:

    var book = new Array();
    
    var booktemp = {
       "id" : "po-0167",
       "date" : new Date(1980, 2, 24),
       "quantity" : 1,
       "amount" : 4,
       "title" : "A Book About Nothing"
    };  
    
    book.push(booktemp);  
    

    PS.
    var arr = [] and var arr = new Array() are the same Not all browsers works well with var arr = []

    0 讨论(0)
  • 2020-12-09 23:04

    I tried and found the solution to it, since the att and values will be object after i push it

    var temp = new Object();
        temp["id"] = "po-0167";
        temp["date"] = new Date(1980, 2, 24);
        temp["quantity"] = 1;
        temp["amount"] = 4;
        temp["title"] = "A Book About Nothing";
    
    bookorders.push(temp);
    

    this will make it display in the datatable, the generic part will just be iterated through using the temp[att] = attributes[att];

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