Js conversion problem: {id: 111, name: 'aaa'} converted to "id=111&name=aaa"

how to convert {id: 111, name: "aaa"} to "id=111&name=aaa"

most conveniently
Mar.06,2021

function toUrlSearch (obj) {
    return new URLSearchParams(obj).toString()
}

it is most convenient to use qs module
https://github.com/ljharb/qs


the querystring; front end of the module that comes with nodejs should have a similar library

var querystring = require('querystring');

var obj = { id: 111, name: 'aaa'};  

console.log(querystring.stringify(obj)); // "id=111&name=aaa"

version 1.0

function jsonToQuery(json) {
    let result = [];
    for (let key in json) {
         result.push(key + '=' + json[key]);
    }
    return result.join('&');
};

version 2.0

function jsonToQuery(json, replace){
let result = [];
replace = replace || function(value){
    return value;
}

for(let key in json){
    let item = json[key];

    result.push(key + '=' + replace(json[key]));
}
return result.join('&');

}


/**
 * object
 * @param obj
 * @returns {boolean}
 */
const isPlainObject = obj => {
  if (typeof obj !== 'object' || obj === null) return false;

  let proto = obj;
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }
  return Object.getPrototypeOf(obj) === proto;
};

/**
 * objectarray
 * @param obj
 */
const isObjectOrArray = obj =>
  obj !== null && (Array.isArray(obj) || isPlainObject(obj));

/**
 * dataquery string
 * @param data
 * @returns {string}
 */
const dataToQueryString = (data = null) => {
  let queryString = '';
  if (data !== null) {
    const propsArray = Object.keys(data);
    const queryArray = [];
    propsArray.forEach(props => {
      const value = data[props];
      if (value !== undefined && value !== '') {
        if (isObjectOrArray(value)) {
          queryArray.push(`${props}=${encodeURI(JSON.stringify(value))}`);
        } else {
          queryArray.push(`${props}=${value}`);
        }
      }
    });
    queryString = queryArray.join('&');
  }
  return queryString;
};
Menu