将具有数字键的JavaScript对象转换为数组

2020/10/22 18:21 · javascript ·  · 0评论

我有一个像这样的对象作为服务器的JSON响应返回:

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

我想将其转换为这样的JavaScript数组:

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

有没有最好的方法来做到这一点?无论我在哪里阅读,人们都在使用复杂的循环逻辑。那么有替代方法可以做到这一点吗?

jQuery实际上非常简单 $.map

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

小提琴

而且在没有jQuery的情况下几乎一样容易,将键转换为数组,然后使用 Array.map

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

小提琴

假设它已经被解析为javascript对象,并且实际上不是JSON(JSON是一种字符串格式),在这种情况下,JSON.parse也需要进行遍历

在ES2015中Object.values,可以轻松进行救援

var arr = Object.values(obj);
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]);
}

希望这就是你所追求的!

您只需像

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

演示

就像“ JSON对象”一样,JSON是一种序列化表示法。

如果您想将javascript对象转换为javascript数组,则可以编写自己的循环[不会那么复杂!],或者依赖underscore.js _.toArray()方法:

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();

这里没什么难的。循环遍历对象元素并将其分配给数组

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

http://jsfiddle.net/Qq2aM/

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];
  }
}

console.log(array)

演示

尝试这个:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});
var obj = {"0":"1","1":"2","2":"3","3":"4"};

var vals = Object.values(obj);

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

问题的另一种选择

var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed

使用原始javascript,假设您具有:

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

您可以通过以下方式获取值:

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

输出:

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

不知道我在这里缺少什么,只是尝试下面的代码就可以了。我在这里想念什么吗?

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));
  }
 })

假设您的价值如下

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

然后您可以使用以下代码将其转换为javascript数组

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

这也可以将json转换为多维JavaScript数组。

当使用php json编码的字符串时,此页面上的其他方法似乎对我而言都不完全起作用,除了我在这里提到的方法。

这里是你怎么能拿对象数组的例子,并随后对数组进行排序。

  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];
      }
    );
  }

这是最好的解决方案。我想是这样。

Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
      var data = [];

      data  = {{ jdata|safe }}; //parse through js
      var i = 0 ;
      for (i=0;i<data.length;i++){
         data[i] = data[i].value;
      }

您可以使用PHP将json对象转换为Array&String。

$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++;
}

您可以使用Object.assign()空数组文字[]作为target

const input = {
  "0": "1",
  "1": "2",
  "2": "3",
  "3": "4"
}

const output = Object.assign([], input)

console.log(output)

如果检查polyfillObject.assign(target, ...sources)只需将所有可枚举的自身属性从source对象复制到目标对象。如果target是数组,它将数字键添加到数组文字中并返回该target数组对象。

本文地址:http://javascript.askforanswer.com/jiangjuyoushuzijiandejavascriptduixiangzhuanhuanweishuzu.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!