javascript 将对象展平到数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7660765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:50:36  来源:igfitidea点击:

Flatten object to array?

javascript

提问by Steven Lu

I'm using an object as a hash table. I'd like to quickly print out its contents (for alert()for instance). Is there anything built in to convert a hash into arrays of (key, value) pairs?

我使用一个对象作为哈希表。我想快速打印出它的内容(alert()例如)。是否有内置的东西可以将哈希转换为(键,值)对的数组?

采纳答案by Steven Lu

I updated this some more. This is much easier to parse than even console.log because it leaves out the extra stuff that's in there like __proto__.

我更新了一些。这比 console.log 更容易解析,因为它忽略了那里的额外内容,如__proto__.

function flatten(obj) {
    var empty = true;
    if (obj instanceof Array) {
        str = '[';
        empty = true;
        for (var i=0;i<obj.length;i++) {
            empty = false;
            str += flatten(obj[i])+', ';
        }
        return (empty?str:str.slice(0,-2))+']';
    } else if (obj instanceof Object) {
        str = '{';
        empty = true;
        for (i in obj) {
            empty = false;
            str += i+'->'+flatten(obj[i])+', ';
        }
        return (empty?str:str.slice(0,-2))+'}';
    } else {
        return obj; // not an obj, don't stringify me
    }
}

The only thing I would do to improve this is have it indent correctly based on recursion level.

我唯一要做的就是根据递归级别正确缩进。

回答by megakorre

Since you want to alertit out I assume it's not for your production version, and that old browser compatibility is not an issue.

既然你想要alert它,我假设它不适用于你的生产版本,并且旧的浏览器兼容性不是问题。

If this is the case, then you can do this:

如果是这种情况,那么您可以这样做:

var myHash = ......
alert(Object.keys(myHash).map(function(key) { return [key, myHash[key]]; }));

回答by KooiInc

for quick & dirty use in alertyou could use JSON:

为了快速和肮脏的使用,alert您可以使用JSON

alert(JSON.stringify(yourObj).replace(/,/g,'\n'));

回答by Tim Hong

Here is my version of it. It should allow you to flatten input like below:

这是我的版本。它应该允许您将输入展平,如下所示:

var input = {
   a: 'asdf',
   b: [1,2,3],
   c: [[1,2],[3,4]],
   d: {subA: [1,2]}
}

The function is like this:

函数是这样的:

    function flatten (input, output) {

      if (isArray(input)) {
        for(var index = 0, length = input.length; index < length; index++){
          flatten(input[index], output);
        }
      }
      else if (isObject(input)) {
        for(var item in input){
          if(input.hasOwnProperty(item)){
            flatten(input[item], output);
          }
        }
      }
      else {
        return output.push(input);
      }
    };

    function isArray(obj) {
      return Array.isArray(obj) || obj.toString() === '[object Array]';
    }

    function isObject(obj) {
      return obj === Object(obj);
    }

Usage is something like:

用法类似于:

var output = []

无功输出 = []

flatten(input, output);

展平(输入,输出);

Then output should be the flattened array.

然后输出应该是展平的数组。

回答by Timbergus

Maybe a little late, but here you have my version of the answer, updated to ES2015. I use a recursive function and it works even if there are other objects inside the main object:

也许有点晚了,但是这里有我的答案版本,已更新到 ES2015。我使用递归函数,即使主对象中有其他对象,它也能工作:

function objectFlattener (object) {
  return Reflect.apply(Array.prototype.concat, [], Object.keys(object).map(key => {
    if (object[key] instanceof Object) {
      return objectFlattener(object[key]);
    }
    return `${ key }: ${ object[key] }`;
  }));
}

So changing the last return you can format the element inside your array.

因此,更改最后一个返回值,您可以格式化数组中的元素。

回答by Lightness Races in Orbit

Not that I'm aware of. Still, you can do it yourself fairly concisely:

不是我所知道的。不过,您可以相当简洁地自己完成:

var obj = { a: 1, b: 2, c: 3 };
var arr = [];
for (var i in obj) {
   var e = {};
   e[i] = obj[i];
   arr.push(e);
}
console.log(arr);
// Output: [Object { a=1 }, Object { b=2 }, Object { c=3 }]

Of course, you can't alertthis either, so you might as well just console.log(obj)in the first place.

当然,你也不能alert这样做,所以你不妨一开始就这样做console.log(obj)



You couldoutput arrays of arrays:

可以输出数组数组:

var obj = { a: 1, b: 2, c: 3 };
var arr = [];
for (var i in obj) {
   arr.push([i, obj[i]]);
}
console.log(arr);
// Output: [["a", 1], ["b", 2], ["c", 3]]

alert(arr);
// Alert: a, 1, b, 2, c, 3

But, again, ew.

但是,再次,呃。

回答by m0sa

Use the for loop:

使用 for 循环:

for (var x in yourObj)
{
    alert(yourObj[x]);
}