Aplanar un objeto javascript para pasar como querystring


Tengo un objeto javascript que necesito aplanar en una cadena para que pueda pasar como querystring, ¿cómo lo haría? i. e:

{ cost: 12345, insertBy: 'testUser' } sería cost=12345&insertBy=testUser

No puedo usar jQuery AJAX call para esta llamada, sé que podemos usar eso y pasar el objeto como data pero no en este caso. Sin embargo, usar jQuery para aplanar el objeto estaría bien.

Gracias.

Author: Saxman, 2011-03-31

11 answers

Usted quiere jQuery.param:

var str = $.param({ cost: 12345, insertBy: 'testUser' });
// "cost=12345&insertBy=testUser"

Tenga en cuenta que esta es la función utilizada internamente por jQuery para serializar objetos pasados como argumento data.

 65
Author: lonesomeday,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 19:20:35

Aquí hay una versión que no es de jQuery:

function toQueryString(obj) {
    var parts = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
        }
    }
    return parts.join("&");
}
 77
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-03 08:40:08

Mi versión ES6 (Javascript puro, sin jQuery):

function toQueryString(paramsObject) {
  return Object
    .keys(paramsObject)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`)
    .join('&')
  ;
}
 33
Author: Michaël Perrin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-20 10:51:24

Aquí hay otra versión que no es de jQuery que utiliza lodash o underscore si ya está utilizando una de esas bibliotecas:

var toQueryString = function(obj) {
  return _.map(obj,function(v,k){
    return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  }).join('&');
};
 16
Author: Guy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-01 19:20:09

Pruebe el $.param() método:

var result = $.param({ cost: 12345, insertBy: 'testUser' });
 15
Author: Darin Dimitrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 19:20:11

Esta es una vieja pregunta, pero en la parte superior de las búsquedas de Google, así que estoy agregando esto para completar.

Si 1) no desea usar jQuery, pero 2) desea convertir un objeto anidado en una cadena de consulta, entonces (construyendo a partir de las respuestas de Tim Down y Guy), use esto:

function toQueryString(obj, urlEncode) {
    //
    // Helper function that flattens an object, retaining key structer as a path array:
    //
    // Input: { prop1: 'x', prop2: { y: 1, z: 2 } }
    // Example output: [
    //     { path: [ 'prop1' ],      val: 'x' },
    //     { path: [ 'prop2', 'y' ], val: '1' },
    //     { path: [ 'prop2', 'z' ], val: '2' }
    // ]
    //
    function flattenObj(x, path) {
        var result = [];

        path = path || [];
        Object.keys(x).forEach(function (key) {
            if (!x.hasOwnProperty(key)) return;

            var newPath = path.slice();
            newPath.push(key);

            var vals = [];
            if (typeof x[key] == 'object') {
                vals = flattenObj(x[key], newPath);
            } else {
                vals.push({ path: newPath, val: x[key] });
            }
            vals.forEach(function (obj) {
                return result.push(obj);
            });
        });

        return result;
    } // flattenObj

    // start with  flattening `obj`
    var parts = flattenObj(obj); // [ { path: [ ...parts ], val: ... }, ... ]

    // convert to array notation:
    parts = parts.map(function (varInfo) {
        if (varInfo.path.length == 1) varInfo.path = varInfo.path[0];else {
            var first = varInfo.path[0];
            var rest = varInfo.path.slice(1);
            varInfo.path = first + '[' + rest.join('][') + ']';
        }
        return varInfo;
    }); // parts.map

    // join the parts to a query-string url-component
    var queryString = parts.map(function (varInfo) {
        return varInfo.path + '=' + varInfo.val;
    }).join('&');
    if (urlEncode) return encodeURIComponent(queryString);else return queryString;
}

Use como:

console.log(toQueryString({
    prop1: 'x',
    prop2: {
        y: 1,
        z: 2
    }
}, false));

Que produce:

prop1=x&prop2[y]=1&prop2[z]=2
 14
Author: Jrop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-14 19:37:05

Otra versión:

function toQueryString(obj) {
    return Object.keys(obj).map(k => {
      return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
    })
    .join("&");
}
 4
Author: blablabla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-21 17:58:53
var myObj = { cost: 12345, insertBy: 'testUser' },
    param = '',
    url   = 'http://mysite.com/mypage.php';    

for (var p in myObj) {
  if (myObj.hasOwnProperty(p)) {
    param += encodeURIComponent(p) + "=" + encodeURIComponent(myObj[p]) + "&";
  }
}

window.location.href = url + "?" + param;
 3
Author: mVChr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 19:23:49

JavaScript general:

function toParam(obj) {
  var str = "";
  var seperator = "";
  for (key in obj) {
    str += seperator;
    str += enncodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
    seperator = "&";
  }
  return str;
}


toParam({ cost: 12345, insertBy: 'testUser' })
"cost=12345&insertBy=testUser"
 3
Author: Jim Blackler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 19:24:15

Puedes usar esto

function serialize(obj)
{
    let str = []

    for(var p in obj)
    {
      if(obj.hasOwnProperty(p)) str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
    }

    return str.join('&')
}

Pruebe JSFiddle en este enlace https://jsfiddle.net/yussan/kwmnkca6 /

 1
Author: yussan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 09:12:50

Versión ES6 de La respuesta de Jrop (también analiza los parámetros anidados)

const toQueryString = (obj, urlEncode = false) => {
  if (!obj) return null;
  const flattenObj = (x, path = []) => {
    const result = [];
    Object.keys(x).forEach((key) => {
      if (!Object.prototype.hasOwnProperty.call(x, key)) return;
      const newPath = path.slice();
      newPath.push(key);
      let vals = [];
      if (typeof x[key] === 'object') {
        vals = flattenObj(x[key], newPath);
      } else {
        vals.push({ path: newPath, val: x[key] });
      }
      vals.forEach((v) => {
        return result.push(v);
      });
    });
    return result;
  };

  let parts = flattenObj(obj);
  parts = parts.map((varInfo) => {
    if (varInfo.path.length === 1) {
      varInfo.path = varInfo.path[0]; // eslint-disable-line no-param-reassign
    } else {
      const first = varInfo.path[0];
      const rest = varInfo.path.slice(1);
      varInfo.path = `${first}[${rest.join('][')}]`; // eslint-disable-line no-param-reassign
    }
    return varInfo;
  });

  const queryString = parts.map((varInfo) => {
    return `${varInfo.path}=${varInfo.val}`;
  }).join('&');
  if (urlEncode) {
    return encodeURIComponent(queryString);
  }
  return queryString;
};
 1
Author: Mythical Fish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-25 14:56:40