Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Only add a object node to an existing object if a specific condition is set

I get some data from the database using the following sql command:

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

the response would look like this:

Response from sql query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now I create a Json stringified object to use it later on using the following code:

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);

My problem is that the following part:

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

should only be added if penalty, reason, admin, dateOfBan have values unlike NULL. How could i archive this since i can’t use a if statement?

To create a if statement

>Solution :

You can have an if

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading