json 仅当设置了特定条件时才向现有对象添加对象节点

cnh2zyt3  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(86)

我使用以下sql命令从数据库中获取一些数据:

SELECT users.skin, users.name, users.money, users.money_bank, users.fraction_id, users.fraction_id2, users.family_id, users.online_time, ban_list.ban_from, ban_list.ban_to, ban_list.count, ban_list.datetime, ban_list.reason FROM users LEFT OUTER JOIN ban_list ON users.name = ban_list.ban_to WHERE users.social = ? LIMIT 3

响应将如下所示:
Response from sql query
现在,我创建一个Json字符串化对象,以便稍后使用以下代码:

let charackters = [];

let nameData =  row['name'].split(" ");

charackters.push({
    spawnIndex: 0,
    name: nameData[0],
    surname: nameData[1],
    level: 0,
    cash: row['money'],
    bank: row['money_bank'],
    gender: gender,
    fraction: fraction,
    family: row['family_id'],
    playedTime: row['online_time'],
    ban: {
        penalty: row['count'],
        reason: row['reason'],
        admin: row['ban_from'],
        dateOfBan: row['datetime']
    }
});

let charackterObject = {
    characters: charackters
}
  
let charackterJson = JSON.stringify(charackterObject);

我的问题是以下部分:

ban: {
    penalty: row['count'],
    reason: row['reason'],
    admin: row['ban_from'],
    dateOfBan: row['datetime']
}

只有当penalty,reason,admin,dateOfBan的值不为NULL时才应该添加。既然我不能使用if语句,我该如何存档呢?
创建if语句

kxxlusnw

kxxlusnw1#

你可以有一个如果

const obj = {
  spawnIndex: 0,
  name: nameData[0],
  surname: nameData[1],
  level: 0,
  cash: row['money'],
  bank: row['money_bank'],
  gender: gender,
  fraction: fraction,
  family: row['family_id'],
  playedTime: row['online_time']
 }
 const ban = {};
 if (row['count']) ban["penalty"] = row['count'];
 if (row['reason']) ban["reason"] = row['reason'];
 if (row['ban_from']) ban["admin"] = row['ban_from'];
 if (row['datetime']) ban["dateOfBan"] = row['datetime'];
 if (Object.keys(ban).length > 0) obj["ban"] = ban;
 
 charackters.push(obj);
wwwo4jvm

wwwo4jvm2#

下面是当对象被推送到charackters上时的操作方法:

// Create the ban object
const ban = {
  penalty: row["count"],
  reason: row["reason"],
  admin: row["ban_from"],
  dateOfBan: row["datetime"],
};

// Only add the `ban` object as a property if all 
// of the properties of the `ban` object have a value.
charackters.push({
  spawnIndex: 0,
  name: nameData[0],
  surname: nameData[1],
  level: 0,
  cash: row["money"],
  bank: row["money_bank"],
  gender: gender,
  fraction: fraction,
  family: row["family_id"],
  playedTime: row["online_time"],
  ...(Object.values(ban).every((value) => value) ? { ban } : {}),
});

相关问题