Home > Back-end >  TypeScript: List of header/value -> List ob objects [closed]
TypeScript: List of header/value -> List ob objects [closed]

Time:10-07

Is there some "nice" way to build out of a array of key and value a list of objects in TypeScript?

let heads : string [] = ["name", "addr", "age"];
let vals : string [][] = [["sam", "NY", "30"],["chris", "WY", "22"],["sue"," "TX", "55"]];

What I need:

[{"name": "sam", "addr": "NY", "age": "30"},
 {"name": "chris", "addr": "WY", "age": "22"},
 {"name": "sue", "addr": "TX", "age": "55"}]

CodePudding user response:

Merge each array in vals with heads and create an object with Object.fromEntries:

let heads = ["name", "addr", "age"];
let vals = [["sam", "NY", "30"],["chris", "WY", "22"],["sue", "TX", "55"]];

const result = vals.map(val => Object.fromEntries(heads.map((head, idx) => [head, val[idx]])));
console.log(result);

CodePudding user response:

Array.map can get the result.

let heads = ["name", "addr", "age"];
let vals = [["sam", "NY", "30"], ["chris", "WY", "22"], ["sue", "TX", "55"]];

const result = vals.map((item) => {
   let newItem = {};
   item.forEach((value, index)=> {
      newItem[heads[index]] = value;
   });
   return newItem;
});

console.log(result);

  • Related