Javascript 如何将数组数组映射到具有给定键数组的对象数组?

Javascript 如何将数组数组映射到具有给定键数组的对象数组?,javascript,lodash,Javascript,Lodash,从键的数组和数组的数组中,如下所示: const keys = ['foo', 'bar']; const vals = [ ['a', 'A'], ['b', 'B'] ]; 如何获得如下所示的对象数组 [ {'foo' : 'a', 'bar' : 'A'}, {'foo' : 'b', 'bar' : 'B'} ] 也许使用lodash?你可以简单地使用reduce let key=['foo','bar']; 设值=[ ['a','a'], ['b','b'] ];

从键的数组和数组的数组中,如下所示:

const keys = ['foo', 'bar'];
const vals = [
  ['a', 'A'],
  ['b', 'B']
];
如何获得如下所示的对象数组

[
  {'foo' : 'a', 'bar' : 'A'},
  {'foo' : 'b', 'bar' : 'B'}
]

也许使用
lodash

你可以简单地使用
reduce

let key=['foo','bar'];
设值=[
['a','a'],
['b','b']
];
const res=values.reduce((a,[第一,第二])=>{
返回[…a,{[keys[0]]:first,[keys[1]]:second}];
}, []);
控制台日志(res)
.as console wrapper{min height:100%!important;top:0}
您可以使用loash从二维数组中每个值数组的键和值数组创建对象,方法如下:

const key=['foo','bar']
常数=[
['a','a'],
['b','b']
];
const res=u.map(vals,arr=>u.zipObject(key,arr));
控制台日志(res)

为了更通用,您可以将
Array.reduce()
index
变量一起使用

const key=['foo','bar']
常量值=[
['a','a'],
['b','b']
]
const mapped=values.map(val=>val.reduce((acc,cur,i)=>({…acc,[keys[i]]]:cur}),{}))
console.log(映射)
let dataKeys=['foo','bar'];
让数据值=[
['a','a'],
['b','b']
];
let transformed=dataValues.reduce((结果,项)=>{
结果:推(
数据键.reduce((r,dk,index)=>{
设o={};
o[dk]=项目[索引];
返回{…r,…o}
},{})
)
返回结果
},[]);

log(JSON.stringify(transformed,null,2))
使用lodash/fp,您可以使用
.flow()
生成一个函数,该函数使用
生成
.zipObject()
,使用curried
.zipObject()生成
.map()
生成
.map()
,然后可以使用
VAL
调用该函数以获取对象数组:

const fn=u.flow(u.zipObject,u.map);
常量键=['foo','bar']
常数=[
['a','a'],
['b','b']
];
常数结果=fn(键)(VAL);
控制台日志(结果)

你能分享你试过的代码吗。使用
map
是不正确的,有人能说出为什么使用map是不正确的吗?为什么你认为使用
map
是不正确的?OP正在尝试将数组的项映射到某些值。
map
将返回与主数组长度相等的元素,但最终结果长度可能不等于初始长度。否。外部数组有2项(子数组),最终数组也有2项(对象)。如果外部数组将具有
n
项,则最终数组也将具有
n
项是,但仅限于此处。