如何从单个数组对象中的多个数组对象创建数组?

时间:2019-02-05 06:04:01

标签: javascript jquery arrays

希望大家都做得很好,目前我陷入一个问题,尝试用可能的方法来生成合适的数组对象组合,这对于我的csv下载是可行的。

我有一个数组类型:-

[Array(4),Array(10),Array(2),Array(15),..]

展开它显示如下:-

var arr= [

[{life_events: "Started studying at Escola Universitària Formatic Barcelona"}, {life_events: "Got a Pet"}, {life_events: "Travelled"}],
[{bio: "No additional details to show"}],
[{places_relationship: ""}],
[{contact_info: "Birthday6 May 1995"}, {contact_info: "No contact info to show"}],
[{places_living: "Barcelona, Spain"}],
[{overviewsection: "Works at En Mi Casa"}],
[{overviewsection: "Studies Dirección Formatic Barcelona"}]]

上述数组对象的预期输出:-

 [
{life_events: "Started studying at Escola Universitària Formatic Barcelona",bio: "No additional details to show",places_relationship: "", contact_info: "Birthday6 May 1995", places_living: "Barcelona, Spain", overviewsection: "Works at En Mi Casa",overviewsection: "Studies Dirección Formatic Barcelona"},
{life_events: "Got a Pet",bio: "No additional details to show",places_relationship: "", contact_info: "No contact info to show", places_living: "Barcelona, Spain", overviewsection: "Works at En Mi Casa",overviewsection: "Studies Dirección Formatic Barcelona"}
]

请告诉我,哪种是从上述数组中获得这种结果的最佳解决方案。

请以此为例来理解我的查询:-

是的,请检查以下内容:-考虑输入示例:-

[ { a : 1 },{ a : 2 } ] [ { b : 1 } , { b : 2 } ] [ { c : 1 },{ c : 2 } ]

输出应类似于:-`[{a:1,b:1,c:1},{a:2,b:2,c:2}]

我也正在共享我的代码,请检查:-

function convertArrayOfObjectsToCSV(args) {  
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;
        data = args.data || null;

        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });
        return result;
    }   

    function downloadCSV(args, stockData) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: stockData
        });
        if (csv == null) return;

        filename = args.filename || 'data.csv';
        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        jQuery.trim(csv);
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }

    function merge_data(){
        var my_main_arry = [];
        chrome.storage.local.get('overviewsection_data', function(data) {
            var data = data.overviewsection_data;
            console.log('i am here', data); // here the data contains that array.
            var opts = {};

            $(data).each(function(key,value){
                $(value).each(function(i,val){
                    $.extend(opts,val); // i tried to fix by using this but its not working as expected
                    my_main_arry.push(opts);
                })
            })
            console.log('my main array', my_main_arry);
            downloadCSV('data.csv', my_main_arry);
        });
    }

谢谢!

4 个答案:

答案 0 :(得分:1)

我不确定这是否是您想要的。您可以使用Array.fromreducespread syntax做这样的事情:

const input = [
  [{ a: 1 }, { a: 2 }],
  [{ b: 1 }, { b: 2 }],
  [{ c: 1 }, { c: 2 }]
]

const maxLength = Math.max(...input.map(a => a.length))

const output = 
    Array.from({length: maxLength},
               (_, i) => ({ ...input.reduce((r, a, i1) => ({ ...r, ...a[i] }), {}) }))

console.log(output)

答案 1 :(得分:1)

我幼稚的解决方案是:

var initialArray = [
  [ { a : 1 }, { a : 2 }, { a : 3 } ],
  [ { b : 1 }, { b : 2 } ],
  [ { c : 1 },{ c : 2 } ]
];


function sortArray(arr) {
  var maxEntries = 0; // Num of arrays you will have at the end
  var baseObj = {}; // baseObj will be = { a: '', b: '', c: '' }
  
  arr.forEach(function(collection) {
    if(collection.length > maxEntries) maxEntries = collection.length;
    var currentKey = Object.keys(collection[0])[0]; // Get the key name to store it in baseObj
    baseObj[currentKey] = ''; // Default value
  });

  var newArray = [];

  for(var i = 0; i < maxEntries; i++) {
    newArray.push(Object.create(baseObj)); // Shallow copy of baseObj
    
    arr.forEach(function(collection) {
      if(collection[i]) {
        newArray[i] = Object.assign(newArray[i], collection[i]); // Replace with the value
      }
    });
  }
  
  return newArray;
}

console.log("Result :", sortArray(initialArray));

您将获得:[ {a: 1, b: 1, c: 1}, {a: 2, b: 2, c: 2}, {a: 3, b: '', c: ''} ]

答案 2 :(得分:0)

STEPS:

  1. 创建一个数组来存储结果。
  2. 为每个life_events进行迭代。
  3. 在每次迭代中使用索引从其他数组构造具有每个属性的对象。
  4. 将对象放入结果数组。

答案 3 :(得分:0)

    
  var arr = [
      [ {"a": 1},{"d": 2} ],
      [ {"c": 3}]
    ]
    
    var combinedArr = arr.reduce((acc, element) => (acc.push(...element), acc), [])
    console.log(combinedArr)