简体   繁体   中英

Javascript - nested arrays transformed to array of objects

I have a nested array data structure like this -

var arrays = [
        [
            ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
        ],
        [
            ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
        ]
    ];

and I need to transform this into an array of objects -

[
        {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
        {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
    ]..



    My code below gives- 

    function objectArray(arr) {
      var obj1 ={};
      var empData=[];
        for (var i = 0; i < arr.length; i++)
        {
            if (Array.isArray(arr[i]))
                { 
                  arr[i].reduce(function(acc,prd){
                   // console.log(prd);
                       console.log(acc.key=prd[0],acc.Value=prd[1]);//--> output shown below
                       return acc;
                  },{});
                }
        }
    }

     var returnArrayOfObjs = objectArray(arrays);
     var empData = [];
     empData.push(returnArrayOfObjs);
     console.log(empData);  

The above log statement gives me an [undefined] as shown below in my output -

The output I get is as below - What am I doing wrong? Pls help!

firstName Joe
lastName Blow
age 42
role clerk
firstName Mary
lastName Jenkins
age 36
role manager
[undefined]

Iterate the array with Array#map , and Array#reduce each sub array to an object.

 const arr = [[["firstName","Joe"],["lastName","Blow"],["age",42],["role","clerk"]],[["firstName","Mary"],["lastName","Jenkins"],["age",36],["role","manager"]]]; const result = arr.map((subArr) => subArr.reduce((obj, [key, value]) => { obj[key] = value; return obj; }, {})); console.log(result); 

I wrote a forEach() solution but map() / reduce() is probably more elegant so I upvoted @OriDrori :) Just posting this for comparison.

 var arrays = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']] ]; var rst = []; arrays.forEach(function(item){ var obj = {}; item.forEach(function( subitem, index ){ obj[ subitem[0] ] = subitem[1] }); rst.push(obj); }); console.log( rst ); 

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