将数组添加到对象
adding array to Object
我正在尝试遍历 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 ""
});
});
如果要将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'];
});
});
相关文章:
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- Meteor-将选定窗体中的对象添加到集合中
- 在play2框架中向json对象添加下拉列表项
- 如何在javascript上向数组的对象添加新元素
- JSON到对象数组,并向每个对象添加项
- 如何将一个对象添加到每个对象数组中
- 向Angular作用域对象添加对象数组——TypeError
- CoffeeScript将对象添加到数组中
- 如何从Addon SDK向选项卡对象添加进度侦听器
- 使用ja将对象添加到HTML画布中
- 向通过ReST JSON调用生成的Angular Javascript对象添加方法
- 将新对象添加到本地存储
- 为什么可以'我们在函数体中为函数对象添加属性,就像在javascript中为对象文字添加属性一样
- 使用游标循环将JS对象添加到数组中
- 向调用全局javascript函数的对象添加处理程序
- 将另一个文件中的对象添加到单独文件中的阵列中
- 将对象添加到数组中
- 为新对象添加函数,将对象添加到数组中.理解困难'这'关键字
- sequelize为找到的对象添加值
- 向对象添加新方法和值,同时避免重复