简体   繁体   中英

how to construct a query from an object using keys and values - Javascript

I want to convert an object containing keys and values into a string of query, something like:

obj1: {
  abc: "Abc",
  id: 1,
  address: "something"
}.

however this object is dynamically created, hence the number and the keys in it may vary, like another obj dynamically could be;

obj1: {
  test: "123",
  test2: "3333"
}

whatever object does the server return I need to convert this into a string of query/; like

query1 = "test:'123'and test2: '3333'"
query2 = "abc:'Abc' and id: 1 and address: 'something'"

I could simpley try:

Object.keys(obj1)[0]
Object.keys(obj1)[1]
Object.keys(obj1)[2]

and get the keys and use:

Object.keys(obj1)[0]: obj1[Object.keys(obj1)[0]]

this would give me:

abc:'Abc'

however since the length of the keys in the object is not static and nor are the keys I'm finding it difficult to know how to concatenate these values into one string out of this any idea?

There are some minor inconsistencies in your format, but disregarding those you can use Object.entries , Array#map and Array#join as follows:

 const objToQuery = o => Object.entries(o).map(([k, v]) => `${k}: ` + (typeof v === "number" ? v : `'${v}'`) ).join(" and ") ; const obj1 = { abc: "Abc", id: 1, address: "something" }; const obj2 = { test: "123", test2: "3333" }; console.log(objToQuery(obj1)); console.log(objToQuery(obj2));

Just being a bit creative here and using built in URLSearchParams() then replacing the = and the & . Not sure how important your quotes are as the other solution is more efficient if they are needed

 const obj1 = { abc: "Abc", id: 1, address: "something" } const objToQuery = o => { return (new URLSearchParams(Object.entries(o))) .toString().replace(/=/g, ': ').replace(/&/g, ' and ') } console.log(objToQuery(obj1))

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