如何创建在单个阵列中的多个对象数组对象数组?

问题描述 投票:0回答:4

希望大家都做得很好,目前我被困在发现产生合适的数组对象的组合这是我的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},{一个: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);
        });
    }

提前致谢!

javascript jquery arrays
4个回答
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: ''} ]


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)

0
投票

脚步:

  1. 建立一个数组来存储结果。
  2. 迭代你有每个life_events
  3. 构建使用在每次迭代索引从其他阵列中的每个属性的对象。
  4. 推入对象的结果阵列。

0
投票

    
  var arr = [
      [ {"a": 1},{"d": 2} ],
      [ {"c": 3}]
    ]
    
    var combinedArr = arr.reduce((acc, element) => (acc.push(...element), acc), [])
    console.log(combinedArr)
© www.soinside.com 2019 - 2024. All rights reserved.