javascript - 将数组添加到对象

标签 javascript json

我试图遍历 Json 两次:一次用于父元素,然后再次用于更多细节。 (这最终将导出为 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']; 
      });
  });

最佳答案

在评论中阐明您的要求后,解决方案很简单:

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

关于javascript - 将数组添加到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10838746/

相关文章:

json - 如何使用 Oracle 12C JSON_VALUE 提取大于 4000 字节的 json 值?

ruby-on-rails - 如何将 JSON 数组与 Rails JSON 列中的对象一起保存?

javascript - 从 Django 模型获取数据到 Google Charts

json - 是否可以使用 json 的 json_serde::from_str() 获取值,其中字符串周围没有“”?

javascript - GoodData:JavaScript SDK 设置 - repo 克隆错误

javascript - 如何计算循环内的随机输出?

javascript - 将 PHP 重定向到新窗口

javascript - Packery:启用可拖动性和装订线

javascript - 如何执行符合我需要的 Javascript 对象递归搜索?

json - Swagger-ui api(资源)的名字是怎么生成的?