1

I have a table

const header = ["name", "age", "hobby"];
const content = [ ["Eva", 3, "dance"],
                  ["Kevin", 5, "ball"],
                  ...];

How can I get output as an array of objects?

[{name: "Eva", age: 3, hobby: "dance"}, 
 {name: "Kevin", age: 5, hobby: "ball"},
 ...]
3
  • By table, you mean an actual HTML table (and that's just your representation of it's content)? Commented Jul 24, 2018 at 3:37
  • My data structure. Commented Jul 24, 2018 at 3:38
  • The following link may help you : stackoverflow.com/questions/12290927/… Commented Jul 24, 2018 at 4:24

3 Answers 3

1

Lodash (or underscore.js) library provides some nice functions to transform data. It's just one line:

import _  from 'lodash';
const output = content.map((row) => _.zipObject(row, header));
Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to point out that the arguments for row and header should be swapped (header coming first).
1

You can do like this with javascript :

const header = ["name", "age", "hobby"];
const content = [["Eva", 3, "dance"],
 ["Kevin", 5, "ball"]
];
const result = [];

for (var i = 0; i < content.length; i++) {
 var obj = {};
 for (var j = 0; j < header.length; j++) {
  obj[header[j]] = content[i][j];
 }
 result.push(obj);
}
console.log(result);

Comments

0

can be done with map and reduce

const header = ["name", "age", "hobby"];
const content = [
  ["Eva", 3, "dance"],
  ["Kevin", 5, "ball"]
];

console.log(content.map((item) => {
  return header.reduce((acc, cur, i) => {
    acc[cur] = item[i];
    return acc;
  }, {});
}));

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.