我有一个JSON对象可供我使用,如下所示:
{
"Fields": [
{
"table": "catalogue",
"field": "Histo_Qtite",
"type": "STRING"
},
{
"table": "catalogue",
"field": "id_article",
"type": "STRING"
},
{
"table": "contact",
"field": "contact_email",
"type": "STRING"
},
{
"table": "contact",
"field": "contact_firestname",
"type": "STRING"
},
{
"table": "customer",
"field": "activity_type",
"type": "STRING"
},
{
"table": "customer",
"field": "adress",
"type": "STRING"
}
],
"Tables": [
{
"entity": "CATALOGUE",
"table": "catalogue"
},
{
"entity": "CLIENT",
"table": "customer"
},
{
"entity": "CONTACT",
"table": "contact"
}
]
}
我正在尝试根据表名为每个“Fields”对象创建一个多维数组。为此,我尝试了javascript,结果就是这个代码:
var objectPREFIX = "object_",
selectedObject = '',
objectArray = [],
objectImport = [],
OFImport = [],
TablesLength = jsonImport.Tables.length,
FieldsLength = jsonImport.Fields.length;
for (i = 0; i < FieldsLength; i++) {
selectedObject = objectPREFIX + jsonImport.Fields[i].table;
OFImport[selectedObject] = {
tableName : jsonImport.Fields[i].table,
FieldName : jsonImport.Fields[i].field,
fieldType : jsonImport.Fields[i].type
}
for (j = 0; j < TablesLength; j++) {
if(OFImport[selectedObject].tableName == jsonImport.Tables[j].table) {
objectImport.push(OFImport[selectedObject]);
objectArray[selectedObject] = OFImport[selectedObject];
}
}
}
console.log(objectArray);
我理解的问题是OFImport[selectedObject]
包含“Fields”的每个对象迭代,并且只显示控制台中的最后一个对象。
我想知道如何在“Fields”和“Tables”之间建立一个比较条件,以便在每个迭代中使用不同的数组。
这是一个FIDDLE来证明这个问题(对不起,如果我有麻烦说明我的解释)。
答案 0 :(得分:1)
如果我理解你要做什么,哪个有一个表数组,哪个有一个字段数组,那么我认为你的for
循环向后。
你需要先循环你的表,然后像这样添加你的字段: -
jsonImport = {
"Fields": [{
"table": "catalogue",
"field": "Histo_Qtite",
"type": "STRING"
}, {
"table": "catalogue",
"field": "id_article",
"type": "STRING"
}, {
"table": "contact",
"field": "contact_email",
"type": "STRING"
}, {
"table": "contact",
"field": "contact_firstname",
"type": "STRING"
}, {
"table": "customer",
"field": "activity_type",
"type": "STRING"
}, {
"table": "customer",
"field": "adress",
"type": "STRING"
}],
"Tables": [{
"entity": "CATALOGUE",
"table": "catalogue"
}, {
"entity": "CLIENT",
"table": "customer"
}, {
"entity": "CONTACT",
"table": "contact"
}]
}
var objectArray = [],
objectPREFIX = "object_",
selectedObject = '',
TablesLength = jsonImport.Tables.length,
FieldsLength = jsonImport.Fields.length;
for (i = 0; i < TablesLength; i++) {
selectedObject = objectPREFIX + jsonImport.Tables[i].table;
objectArray[selectedObject] = {
table: jsonImport.Tables[i].table,
entity: jsonImport.Tables[i].entity,
Fields: []
}
for (j = 0; j < FieldsLength; j++) {
if (jsonImport.Tables[i].table == jsonImport.Fields[j].table) {
objectArray[selectedObject].Fields.push({
"field": jsonImport.Fields[j].field,
"type": jsonImport.Fields[j].type
});
}
}
}
console.log(objectArray);
&#13;
输出: -