我正在解析XML
文件并构建一个对象数组。我得到具有相同ID的对象,并且我想将它们添加到另一个ID所在的INDEX
。
我尝试通过ID和.push
对象检查同一个INDEX,但它不起作用。
if (myData[object.ID] = null)
myData[object.ID] = object;
else {
myData[object.ID].push(object);
}
任何想法我怎样才能做出这样的事情?
myData[0] = {ID: "133", text: "car 1"}
myData[1] = {ID: "143433", text: "car 34"}
myData[2] = {ID: "55", text: "car 12"}
myData[3] = {ID: "66", text: "car51"}, {ID: "66", text: "car56"}, {ID: "66", text: "car 323"}
myData[4] = {ID: "32323", text: "car132"}
修改
经过尝试@ sebcap26,@ antur123回答:
if (myData[object.ID] = null) {
myData[object.ID] = [];
}
myData[object.ID].push(object);
我得到的结果是这样的:
myData[undefined × 1,Array[3], Array[1], undefined × 1, Array[3],undefined × 1,undefined × 1,undefined × 1,undefined × 1,Array[1]]
如何删除undefined?
答案 0 :(得分:1)
您可以将数组存储在“myData”对象的每个索引中,如下所示:
if (myData[object.ID] = null) {
myData[object.ID] = [];
}
myData[object.ID].push(object);
产生的“myData”将是:
myData[0] = [{ID: "133", text: "car 1"}]
myData[1] = [{ID: "143433", text: "car 34"}]
myData[2] = [{ID: "55", text: "car 12"}]
myData[3] = [{ID: "66", text: "car51"}, {ID: "66", text: "car56"}, {ID: "66", text: "car 323"}]
myData[4] = [{ID: "32323", text: "car132"}]
如果只想存在多个数组,而只是存在一个数组,那么代码将是这样的:
if (myData[object.ID] = null) {
// If index is empty, store object
myData[object.ID] = object;
} else if (typeof(myData[object.ID]) === 'array') {
// If index has an array, add object to array
myData[object.ID].push(object);
} else {
// If index has an object, create an array and store
// both "old" and "new" objects
var oldObject = myData[object.ID];
myData[object.ID] = [];
myData.push(oldObject);
myData.push(object);
}
然而,这会导致一种奇怪的数据结构,对于每个对象索引,您有时会有一个数组,有时候是一个对象。有点难以处理和使用......
在这种情况下产生的“myData”将是:
myData[0] = {ID: "133", text: "car 1"}
myData[1] = {ID: "143433", text: "car 34"}
myData[2] = {ID: "55", text: "car 12"}
myData[3] = [{ID: "66", text: "car51"}, {ID: "66", text: "car56"}, {ID: "66", text: "car 323"}]
myData[4] = {ID: "32323", text: "car132"}
答案 1 :(得分:0)
您必须使用对象(如关联数组)将id用作键。每个值都是一个数组。
您不能使用数组对其进行索引,因为您使用的是ID,而不是索引。这很重要,因为如果你试图在myData[143433]
是一个数组时设置myData
,那么它会起作用,但它会创建一个包含143434个未定义元素的数组,这不是你想要的做...
var myData = {};
if(!myData[object.ID]) {
myData[object.ID] = [];
}
myData[object.ID].push(object);
结果如下:
var myData = {
"133": [
{ID: "133", text: "car 1"}
],
"143433": [
{ID: "143433", text: "car 34"}
],
"55": [
{ID: "55", text: "car 12"}
],
"66": [
{ID: "66", text: "car51"},
{ID: "66", text: "car56"},
{ID: "66", text: "car 323"}
],
"32323": [
{ID: "32323", text: "car132"}
]
};