object(后台返回的json数据) 转 array

chenshun
  • 300
  1. json对象转数组
  2. 后台返回的数据格式 {first: 1, second: 2, third: 3, fourth: 4, fifth: 5,sixth:6}(多处使用)
    页面需要用到的格式

    [
        {value: 1, name: 'first'},
        {value: 2, name: 'second'},
        {value: 3, name: 'third'},
        {value: 4, name: 'fourth'},
        {value: 5, name: 'fifth'},
        {value: 6, name: 'sixth'}
    ]
 success: function(data,textStatus, xhr) {
            if(data instanceof Object){
                console.log("this a object");
            }
            console.log(data);
            for(var ele in data){
                array.push(data[ele]);
            }
            console.log(array);
            setOp(array);
            setPie(data);// 这里需要使用
            var token = xhr.getResponseHeader("token");
            sessionStorage.setItem("token",token);
            },

3.图片描述

4.已查看的链接

converting-a-js-object-to-an-array-using-jquery

convert-object-to-array-in-javascript

回复
阅读 4.6k
3 个回答
✓ 已被采纳
var origin = {first: 1, second: 2, third: 3, fourth: 4, fifth: 5,sixth:6};
var result = Object.entries(origin).map(([key, value]) => {
    return {value: value, name: key};
});
console.log(result);
    var origin = {first: 1, second: 2, third: 3, fourth: 4, fifth: 5,sixth:6};
    var result = Object.keys(origin).map(key=>({value:origin[key],name:key}));

发现答案都是使用的 es6(对于js了解不是很深入,错误勿喷),使用一个非es6的。

  var obj =  {first: 1, second: 2, third: 3, fourth: 4, fifth: 5,sixth:6};
        var objectToArray = function (obj) {
            var _arr = [];
            for (var key in obj) {
                var o = [];
                o.name = key;
                o.value = obj[key];
                _arr.push(o)
            }
            return _arr;
        }
        var da = objectToArray(obj);

        var convert = function (array) {
            var finalData = [];
            for(i=0;i<array.length;i++){
            var text = {name:array[i].name,value:array[i].value};
            finalData.push(text);
            }
            console.log(finalData);
        }
        convert(da);

@轩辕Rowboat 提点,可以将 @czl 的答案改成如下方式:

     var origin = {first: 1, second: 2, third: 3, fourth: 4, fifth: 5, sixth: 6};
    var result = Object.keys(origin).map(function (t) {
        return {value: origin[t], name: t}
    });
    console.log(result)
你知道吗?

宣传栏