1

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]
2
  • You are not storing the result of arr[i].reduce anywhere. Commented Jul 20, 2017 at 17:57
  • @T4rk1n Thank you! Commented Jul 20, 2017 at 18:25

2 Answers 2

2

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 );

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @sauntimo.. I really do like forEach.. easier to read...was just trying to see why my reduce is failing.. thanks for your quick response!
just a quick clarification.. in the above forEach are we not creating the obj every time.. meaning for every item...
Yeah, obj is var scoped to that function, think of it as a temporary store before we put the populated object in to the array
2

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);

4 Comments

+1 for map and reduce...Thanks! I am using reduce too.. but don't know why the final object is not an object but just strings!
@sunnysideup - In your code, inside the reduce you are not attaching the key and value correctly to the object, and you don't store the result of the reduce. So all the reduce does is console.log the strings you see.
thank you v much! so obj.key and obj.Value does not really work.. we need to use bracket notation to attach the key values?
Indeed. You have to assign the value to a key on the object obj[key] = value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.