最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to convert nested object to array of objects in javascript - Stack Overflow

programmeradmin2浏览0评论

I have a data that the structure is like below:

var data = {
    0: {
        user: 1,
        job: "call center"
    },
    1: {
        user: 2,
        job: "programmer"
    }
}

Now I want to convert them to array of objects that looks like this:

[Object {user : 1, job  : call center}, {user : 2, job  : programmer} ]

Is it possible? How can I convert them. Any help, thanks.

I have a data that the structure is like below:

var data = {
    0: {
        user: 1,
        job: "call center"
    },
    1: {
        user: 2,
        job: "programmer"
    }
}

Now I want to convert them to array of objects that looks like this:

[Object {user : 1, job  : call center}, {user : 2, job  : programmer} ]

Is it possible? How can I convert them. Any help, thanks.

Share Improve this question edited Mar 9, 2023 at 17:21 Geoffrey Hale 11.4k5 gold badges45 silver badges49 bronze badges asked Dec 15, 2015 at 2:39 qazzuqazzu 4113 gold badges8 silver badges16 bronze badges 2
  • Is it possible? yes – vol7ron Commented Dec 15, 2015 at 2:41
  • what should I need to do? – qazzu Commented Dec 15, 2015 at 2:41
Add a ment  | 

3 Answers 3

Reset to default 5

Try using map

 var array = $.map(data , function(value, index) {
     return [value];
 });

You can also do it without jQuery:

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

yields

[{user: 1, job: 'call center'}, {user: 2, job: 'programmer'}]
  1. Your Object creation has poor syntax
  2. Below shows you how to do this with a simple for loop, but makes a lot of assumptions (e.g., your object keys are labeled correctly). I would ordinarily use map, but feel that may not be as easy/straightforward for you to understand; so the loop should be simple enough to follow.

var data =  { 0:{
                  user : 1,
                  job  : 'call center'
              },
              1:{
                  user : 2,
                  job  : 'programmer'
              }
            };


var arr  = [],
    keys = Object.keys(data);

for(var i=0,n=keys.length;i<n;i++){
  var key  = keys[i];
  arr[key] = data[key];
}
发布评论

评论列表(0)

  1. 暂无评论