TypeScript:标头/值列表->列出ob对象[关闭]
Posted
技术标签:
【中文标题】TypeScript:标头/值列表->列出ob对象[关闭]【英文标题】:TypeScript: List of header/value -> List ob objects [closed] 【发布时间】:2021-11-27 11:23:44 【问题描述】:在 TypeScript 中,是否有一些“不错”的方法可以从键和值数组构建对象列表?
let heads : string [] = ["name", "addr", "age"];
let vals : string [][] = [["sam", "NY", "30"],["chris", "WY", "22"],["sue"," "TX", "55"]];
我需要什么:
["name": "sam", "addr": "NY", "age": "30",
"name": "chris", "addr": "WY", "age": "22",
"name": "sue", "addr": "TX", "age": "55"]
【问题讨论】:
【参考方案1】:将vals
中的每个数组与heads
合并,并用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);
【讨论】:
【参考方案2】:Array.map
可以得到结果。
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);
【讨论】:
以上是关于TypeScript:标头/值列表->列出ob对象[关闭]的主要内容,如果未能解决你的问题,请参考以下文章