如何在JavaScript中将嵌套对象转换为对象数组 [英] How to convert nested object to array of objects in javascript

查看:70
本文介绍了如何在JavaScript中将嵌套对象转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据,其结构如下:

I have a data that the structure is like below:

var data = Object {
    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.

推荐答案

  1. 您的对象创建语法不佳
  2. 下面向您展示了如何通过简单的for循环来执行此操作,但是进行了许多假设(例如,正确标记了对象键).我通常会使用 map ,但您可能并不容易理解.因此循环应足够简单,易于遵循.
  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];
}

这篇关于如何在JavaScript中将嵌套对象转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆