简体   繁体   English

将 object 中的所有数组合并为一个数组。

[英]Combine all arrays in object into one array.

I'm developing an extension for Google chrome and I'd like to combine all arrays in a certain object into one array instead of them being split.我正在为 Google chrome 开发一个扩展,我想将某个对象中的所有数组合并到一个数组中,而不是将它们拆分。 So right now, my console o所以现在,我的控制台 o

chrome.storage.sync.get(null, function(all) {
// this returns everything in chrome's storage. 
}

It looks something like this in my console:在我的控制台中看起来像这样:

在此处输入图片说明

However, I'd like it to actually have all the arraries combined into one, as such:但是,我希望它实际上将所有数组合并为一个,如下所示:

Object目的

feed_0: Array[364] feed_0:数组[364]

I've tried this:我试过这个:

    chrome.storage.sync.get(null, function(all) {
  var test = {}; test = all;
  delete test['currently.settings'];

console.log(test);

var alpha = [];

var result = 0;
  for(var prop in test) {
    if (test.hasOwnProperty(prop)) {
       var second = alpha.concat(prop);

      console.log(second);
    // or Object.prototype.hasOwnProperty.call(obj, prop)
      result++;
    }
  }

   });

But this returns this:但这会返回:

在此处输入图片说明

Here is how to get one array from the all object:以下是如何从all对象中获取一个数组:

var test = Object.values(all).flat();

In older JavaScript versions, that do not support these functions, go for:在不支持这些功能的旧 JavaScript 版本中,请选择:

var test = Object.keys(all).reduce( (acc, a) => acc.concat(all[a]), [] );

To assign it to a feed_0 property, is of course not the difficulty:将它分配给一个feed_0属性,当然不是难事:

test = { feed_0: test };

You can combine your feed_N arrays into one property using Object.keys and Array#reduce :您可以使用Object.keysArray#reducefeed_N数组合并为一个属性:

 var data = { feed_0: [0, 1, 2], feed_1: [3, 4, 5], feed_2: [6, 7, 8], feed_3: [9, 10, 11] } data = Object.keys(data).reduce(function(result, k) { [].push.apply(result.feed_0, data[k]) return result }, { feed_0: [] }) console.log(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM