2

I was given an array such as this :

data = [
  ['first_name', 'second_name', 'sex'],
  ['Jacob', 'David', 'M'],
  ['Kathryn', 'Gardener', 'F'],
  ['Jamaal', 'Dave', 'Unknown']
].

the solution is to return the array as an object looking something like this :

[
  { first_name: "Jacob", second_name: "David", sex: "M" },
  { first_name: "Kathryn", second_name: "Gardener", sex: "F" }
  {....}
];

I wrote the following code :

var object = {};
var arrays = [];
for (i = 0; i < data.length; i++){
   for (var j = i; j < data.length; j++){
       var keys = data[0][i];
       var values = data [j][i];
       object[keys] = values;
   }
   arrays.push(object);
};

but the output I'm having is :

[
   { 
      first_name :'Jamaal',
      second_name : 'Dave',
      sex : 'unknown'
   },
   { 
      first_name :'Jamaal',
      second_name : 'Dave',
      sex : 'unknown'
   },
   {
      first_name :'Jamaal',
      second_name : 'Dave',
       sex : 'unknown'
   },
   {
      first_name :'Jamaal',
      second_name : 'Dave',
      sex : 'unknown'
    }
];

I've also tried several ways either i end up with being able to create only one object...

3
  • 1
    Are you reading some csv file? Commented Dec 3, 2019 at 11:55
  • 1
    Start your iteration loop from 1 not 0. And use data[0][i] as a keys. Commented Dec 3, 2019 at 11:58
  • 1
    Every index in the output array will point to the same var object = {}; Commented Dec 3, 2019 at 12:00

4 Answers 4

3

You need new object (references) inside of the first loop, otherwise you get the same object for every row.

var data = [ ['first_name', 'second_name', 'sex'], ['Jacob', 'David', 'M'], ['Kathryn', 'Gardener', 'F'], ['Jamaal', 'Dave', 'Unknown']],
    result = [],
    i, j,
    object;

for (i = 0; i < data.length; i++) {
    object = {};                           // take a new object
    for (j = 0; j < data[i].length; j++) { // start from zero
        object[data[0][j]] = data[i][j];   // use j as last key
    }
    result.push(object);
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A shorter approach with Object.fromEntries.

const
    getObjects = ([header, ...data]) => data.map(values =>
        Object.fromEntries(values.map((value, index) => [header[index], value])));

var data = [['first_name', 'second_name', 'sex'], ['Jacob', 'David', 'M'], ['Kathryn', 'Gardener', 'F'], ['Jamaal', 'Dave', 'Unknown']],
    result = getObjects(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

2

you can do something like this

dataToObj=(data)=>{
   let head=data[0];
   let result=[];
   for(let i=1;i<data.length;i++){
      let obj={};
       for(let j=0;j<head.length;j++){
         obj[head[j]]=data[i][j]
       }
     result.push(obj);
 }
 return result;
}

Comments

2
    var data = [
  ['first_name', 'second_name', 'sex'],
  ['Jacob', 'David', 'M'],
  ['Kathryn', 'Gardener', 'F'],
  ['Jamaal', 'Dave', 'Unknown']
]


function createObject(arr){
    var arr2 = [];
    keysArr = arr[0];
    arr.splice(0,1);
    arr.forEach(function(x,i){
        arr2[i] = {};
        arr[i].forEach(function(y,j){
            arr2[i][keysArr[j]] = arr[i][j];
        });
    });
    return arr2;
}

createObject(data);

Comments

1

Since no one have posted a example with map i might as well do that, it's short and sweet!

var data = [['first_name', 'second_name', 'sex'],['Jacob', 'David', 'M'],['Kathryn', 'Gardener', 'F'],['Jamaal', 'Dave', 'Unknown']]

var res = []
data.slice(1).map((x, i) => {
  var obj = {}
  x.map((c, j) => {
    obj[data[0][j]] = x[j]
  })
  res.push(obj)
})

console.log(res)

Comments

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.