11

私は Json を 2 回ループしようとしています。(これは最終的に XML にエクスポートされます) それまでの間、オブジェクトに配列を追加するにはどうすればよいでしょうか? 私の現在のコードは XMLObjectDetail を作成しません

 XMLObject = {};
 var XMLObjectDetail = [];

 $.each(data, function(index, element) {
        XMLObject.CardCode = element['CardCode'] 
        XMLObject.CardName = element['CardName'];
        console.log(XMLObject);

  $.each(element, function(key, value) { 
       XMLObject[[XMLObjectDetail.InvPayAmnt]] = value['InvPayAmnt']; 
      });
  });
4

2 に答える 2

13

コメントでリクエストを明確にした後、解決策は簡単です。

var XMLObject = {};
var XMLObjectDetail = [];
XMLObject["XMLObjectDetail"] = XMLObjectDetail;

あなたはそれを短くすることができます

var XMLObjectDetail, XMLObject = {XMLObjectDetail: XMLObjectDetail = []};

ただし、コードの重大な欠陥について言及する必要があります。

XMLObject = {}; // no var keyword: the variable will be global
var XMLObjectDetail = [];

$.each(data, function(index, element) {
    // I don't know how your data object/array looks like, but your code will be 
    // executed many times
    // For each element, you will overwrite the properties
    XMLObject.CardCode = element['CardCode'] // missing semicolon
    XMLObject.CardName = element['CardName'];
    // so that the final XMLObject will only contain cardcode and -name of the last one
    // It will depend on your console whether you see different objects
    // or the same object reference all the time
    console.log(XMLObject);

    // This part is completey incomprehensible
    // you now loop over the properties of the current element, e.g. CardCode
    $.each(element, function(key, value) { 
        // and again you only overwrite the same property all the time
        XMLObject[[XMLObjectDetail.InvPayAmnt]] = value['InvPayAmnt'];
        // but wait: The property name you try to set is very, um, interesting.
        // first, XMLObjectDetail is still an (empty) Array and has 
        //  no 'InvPayAmnt' property - leads to a undefined
        // then, you build an Array with that [undefined] value as the only item
        // OMG, an array? JavaScript does only allow strings as property names,
        //  so the array will be converted to a string - resulting to the empty string ""
    });
});
于 2012-06-01T00:36:52.873 に答える
3

XMLObject配列にオブジェクトを追加する場合は、次のXMLObjectDetailようにします。

var XMLObject, XMLObjectDetail = [];

 $.each(data, function(index, element) {
        XMLObject=new Object(); //or XMLObject = {};
        XMLObject.CardCode = element['CardCode'] 
        XMLObject.CardName = element['CardName'];
        console.log(XMLObject);

        XMLObjectDetail.push(XMLObject);//ADDED OBJECT TO ARRAY

      //DON'T KNOW WHAT ARE YOU TRYING TO DO HERE?
      $.each(element, function(key, value) { 
           XMLObjectDetail[[XMLObjectDetail.InvPayAmnt]] = value['InvPayAmnt']; 
      });
  });
于 2012-05-31T18:08:51.727 に答える