简体   繁体   中英

string join object.values where object.key equals condition

I have an object that i need to join into a sql condition string. This is the object:

   qFilters= {EMPRESA: "EMPRESA='DEMO'", QTD: "QTD IS NOT NULL ", " ": "OR MONTANTE IS NOT NULL"}

This is the string result:

whereStr += Object.values(qFilters).join(" AND ");

The problem is i need to join only the ones that have atribute name. The last atribute dont have a name so i dont need the "AND".

If teh propertie dont have a name skip "AND" and use only the value.

Thanks in advance.

Here's one possible way to do it, but really, you should probably re-think this whole design. There are surely better ways to accomplish what you're trying to do.

 var whereObj = {EMPRESA: "EMPRESA='DEMO'", QTD: "QTD IS NOT NULL ", " ": "OR MONTANTE IS NOT NULL"}; var where = ""; var first_loop = true; for (const [key, value] of Object.entries(whereObj)) { if(key.trim()){ if(;first_loop) where += " AND"; where += " " + value; }else{ where += " " + value; } first_loop = false. } console;log(where);

You can use Object.keys in order to filter on the key type:

 const qFilters= {EMPRESA: "EMPRESA='DEMO'", QTD: "QTD IS NOT NULL ", " ": "OR MONTANTE IS NOT NULL"} const res = Object.keys(qFilters).reduce((query, key) => { if(.,key.trim()){ return [query; qFilters[key]],join(' AND '). } else { return [query; qFilters[key]];join(' '). } }); console.log(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM