Convertir objeto JavaScript con claves numéricas en matriz


Tengo un objeto como este regresando como una respuesta JSON del servidor:

{"0":"1","1":"2","2":"3","3":"4"}

Quiero convertirlo en una matriz JavaScript como esta:

["1","2","3","4"]

¿hay una mejor manera de hacer esto? Dondequiera que esté leyendo, la gente está usando lógica compleja usando bucles. Entonces, ¿hay métodos alternativos para hacer esto?

Author: Xufox, 2014-01-02

16 answers

Es realmente muy sencillo con jQuery $.map

var arr = $.map(obj, function(el) { return el });

FIDDLE

Y casi tan fácil sin jQuery también, convirtiendo las claves en una matriz y luego mapeando los valores con Array.map

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE

Eso es asumiendo que ya está analizado como un objeto javascript, y en realidad no es JSON, que es un formato de cadena, en ese caso una ejecución a través de JSON.parse sería necesario también.

En ES2015 hay Object.values al rescate, lo que hace que esto sea una brisa

var arr = Object.values(obj);
 312
Author: adeneo,
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-16 07:35:41
var json = '{"0":"1","1":"2","2":"3","3":"4"}';

var parsed = JSON.parse(json);

var arr = [];

for(var x in parsed){
  arr.push(parsed[x]);
}

Espero que esto sea lo que buscas!

 104
Author: benhowdle89,
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-01-02 10:51:54

Simplemente lo haces como

var data = {
    "0": "1",
    "1": "2",
    "2": "3",
    "3": "4"
};
var arr = [];
for (var prop in data) {
    arr.push(data[prop]);
}
console.log(arr);

DEMO

 23
Author: Satpal,
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-01-02 10:53:14

No hay nada como un "objeto JSON" - JSON es una notación de serialización.

Si desea transformar su objeto javascript {[6] } a un matriz javascript , o bien escribir su propio bucle [que no sería tan complejo!], o confías en underscore.js _.toArray() método:

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
 20
Author: moonwave99,
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-01-02 10:53:10

Nada difícil aquí. Haga un bucle sobre sus elementos de objeto y asígnelos a la matriz

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
   arr.push(obj[elem]);
}

Http://jsfiddle.net/Qq2aM /

 9
Author: EoiFirst,
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-01-02 10:52:34
var JsonObj= {"0":"1","1":"2","2":"3","3":"4"};
var array = [];
for(var i in JsonObj) {
    if(JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
        array[+i] = JsonObj[i];
    }
}

DEMO

 8
Author: Tareq Salaheldeen,
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-01-02 10:58:42

Prueba esto:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});
 4
Author: Mohammad Reza Saberi,
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-01-02 10:55:16

Usando javascript sin procesar, supongamos que tiene:

var j = {0: "1", 1: "2", 2: "3", 3: "4"};

Puedes obtener los valores con:

Object.keys(j).map(function(_) { return j[_]; })

Salida:

["1", "2", "3", "4"]
 2
Author: mvallebr,
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-04-23 10:28:46

No estoy seguro de lo que me falta aquí, pero simplemente intentar el siguiente código hace el trabajo. Me estoy perdiendo algo aquí?

Https://jsfiddle.net/vatsalpande/w3ew5bhq /

$(document).ready(function(){

var json = {
   "code" :"1", 
   "data" : { 
    "0" : {"id":"1","score":"44"},
    "1" : {"id":"1","score":"44"}
    }
  };

  createUpdatedJson();

  function createUpdatedJson(){

    var updatedJson = json;

    updatedJson.data = [updatedJson.data];

    $('#jsondata').html(JSON.stringify(updatedJson));


    console.log(JSON.stringify(updatedJson));
  }
 })
 2
Author: Vatsal,
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-02-18 17:25:18

Asumiendo que tienes un valor como el siguiente

var obj = {"0":"1","1":"2","2":"3","3":"4"};

Luego puede convertir esto en una matriz de javascript utilizando la siguiente

var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array

Esto también funciona para convertir json en arrays javascript multi-diminsionales.

Ninguno de los otros métodos en esta página parecía funcionar completamente para mí cuando se trabaja con cadenas codificadas en php json, excepto el método que estoy mencionando aquí.

 1
Author: skidadon,
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-12-31 15:08:23

Aquí hay un ejemplo de cómo se puede obtener una matriz de objetos y a continuación, ordenar la matriz.

  function osort(obj)
  {  // map the object to an array [key, obj[key]]
    return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
      function (keya, keyb)
      { // sort(from largest to smallest)
          return keyb[1] - keya[1];
      }
    );
  }
 1
Author: htmlfarmer,
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-09-01 19:40:04

Esta es la mejor solución. Eso creo.

Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
 1
Author: tutaro,
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-27 02:45:06
var obj = {"0":"1","1":"2","2":"3","3":"4"};

var vals = Object.values(obj);

console.log(vals); //["1", "2", "3", "4"]

Otra alternativa a la pregunta

var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
 1
Author: ASM,
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
2018-01-20 19:08:11

Puede convertir el objeto json en Array & String usando PHP.

$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';

$b=json_decode($data);

$i=0;
while($b->{'resultList'}[$i])
{
    print_r($b->{'resultList'}[$i]->{'displayName'});
    echo "<br />";
    $i++;
}
 1
Author: Manav Akela,
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
2018-06-27 03:01:27
      var data = [];

      data  = {{ jdata|safe }}; //parse through js
      var i = 0 ;
      for (i=0;i<data.length;i++){
         data[i] = data[i].value;
      }
 0
Author: cz game,
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-12-31 20:25:20
var obj=  {"0":"1", "1":"2", "2":"3", "3":"4"};
var arr = [];
var keys = window.jQuery.map(obj, function(value, key) {
  arr.splice(key, 0, value); 
  console.log(arr);
});
 -2
Author: VAYU,
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-02-09 10:32:35