简体   繁体   中英

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. So right now, my console 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]

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:

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

In older JavaScript versions, that do not support these functions, go for:

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:

test = { feed_0: test };

You can combine your feed_N arrays into one property using Object.keys and Array#reduce :

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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