我有5个mysql表,我需要来自几个不同脚本的各种数据,这些脚本都使用位于一列或多列中的id相互引用。
我需要创建一个主查询,以完全复制从mysql导入的数组结构,并且还需要对每个字段进行错误处理,然后再将其写入数组以确定是否需要将该值写入数组,或者将其写为空。
到目前为止,脚本看起来像这样:
const items = [];
// Items
for (let i = 0; i < gameItems.length; i++) {
if (gameItems[i].id) {
items.push({ id: gameItems[i].id });
} else {
items.push({ id: null });
}
if (gameItems[i].identifier) {
items.push({ identifier: if (gameItemParams[i].custom_name)
{
items.push({ custom_name: gameItemParams[i].custom_name });
}
else {
items.push({ custom_name: null }); }
}
}
问题或我缺乏找出如何正确执行代码的逻辑的能力,是为了将多个数据字段附加到数组的同一行中,值必须用逗号分隔。
像上面这样的单个推送将数据添加到下一行,而不是将同一对象呈现给array.length,因为每个字段都有一个新行,而不是将一行附加了10个数据,因此,正确地使array.length无效。将有10行,每行包含1条数据。
是否有一种方法可以对我需要从表中调用的每个字段执行错误处理,或者有另一种方法可以在已压入一行后向同一对象添加数据。
这是新创建的数组的结构形式: https://puu.sh/E7ogn/61c3117d3b.png
这是当前通过单个推送来构造数组的方式: https://puu.sh/E7oh7/422541a70d.png
也许有可能在array.push
中间中断,然后我可以在push block
中添加错误处理,但无法找到是否可以解决的问题。
答案 0 :(得分:0)
问题在于您每次都在推动一个对象。取而代之的是,您需要创建一个具有所有字段的对象,然后将其推入数组。
您的代码的另一个问题是,您可以将if
语句用作asgment语句。您需要使用conditional operator来执行此操作,或者从分配中提取此条件。
const items = [];
// Items
for (let i = 0; i < gameItems.length; i++) {
var object = {};
if (gameItems[i].id) {
object.id = gameItems[i].id;
}
else {
object.id = null;
}
if (gameItems[i].identifier) {
object.identifier = (gameItemParams[i].custom_name) ? items.push({ custom_name: gameItemParams[i].custom_name }); : items.push({ custom_name: null });
}
items.push(object);
}
答案 1 :(得分:0)
根据https://puu.sh/E7oh7/422541a70d.png中提到的数据。 您有
之类的数据gameItems=[{id:0}, {identifier:"master-ball"}, {category_id:34}, {"custom_name":"Master Ball"}];
我建议不要将项目制成数组,而应创建临时对象项目,然后将其压入项目。
let items = [];
let item = {
id:null,
identifier: null,
custom_name: null
};
for (let i = 0; i < gameItems.length; i++) {
if (gameItems[i].id !== undefined) {
item.id = gameItems[i].id;
}
if (gameItems[i].identifier !== undefined) {
item.identifier = gameItems[i].identifier;
}
if (gameItems[i].custom_name !== undefined) {
item.custom_name = gameItems[i].custom_name;
}
}
items.push(item);