简体   繁体   English

如何将 map 数组 arrays 转换为具有给定键数组的对象数组?

[英]How to map an array of arrays into an array of objects with a given keys array?

From an array of keys and an array of arrays , like this:数组和 arrays 数组中,如下所示:

const keys = ['foo', 'bar'];
const vals = [
  ['a', 'A'],
  ['b', 'B']
];

How to get an array of objects like below?如何获得如下的对象数组

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

Maybe using lodash ?也许使用lodash

You can use loash's _.zipObject() to create an object from an array of keys and values for each value array inside your 2d array using the _.map() method:您可以使用 loash 的_.zipObject()使用_.map()方法从二维数组中每个值数组的键和值数组创建 object:

 const keys = ['foo', 'bar'] const vals = [ ['a', 'A'], ['b', 'B'] ]; const res = _.map(vals, arr => _.zipObject(keys, arr)); console.log(res);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

If you prefer vanilla JS, then you could use Object.fromEntries() on a zipped array (created using .map() ):如果您更喜欢 vanilla JS,那么您可以在压缩数组(使用.map()创建)上使用Object.fromEntries() ) :

 const keys = ['foo', 'bar'] const vals = [ ['a', 'A'], ['b', 'B'] ]; const res = vals.map( arr => Object.fromEntries(arr.map((v, i) => [keys[i], v])) ); console.log(res);

To be more generic, you can use Array.reduce() with index variable为了更通用,您可以将Array.reduce()index变量一起使用

 const keys = ['foo', 'bar'] const values = [ ['a', 'A'], ['b', 'B'] ] const mapped = values.map(val => val.reduce((acc, cur, i) => ({...acc, [keys[i]]: cur}),{})) console.log(mapped)

With lodash/fp you can generate a function using _.flow() , that curries _.zipObject() with the keys , and the _.map() with the curried _.zipObject() , and then you can call it with vals to get the array of objects:使用 lodash/fp,您可以使用_.flow()生成 function ,使用keys _.zipObject( _.zipObject()_.map()和咖喱_.zipObject() ,然后您可以使用vals获取对象数组:

 const fn = _.flow(_.zipObject, _.map); const keys = ['foo', 'bar'] const vals = [ ['a', 'A'], ['b', 'B'] ]; const result = fn(keys)(vals); console.log(result);
 <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

You can do it simply using reduce .您可以简单地使用reduce来做到这一点。

 let keys = ['foo', 'bar']; let values = [ ['a', 'A'], ['b', 'B'] ]; const res = values.reduce((a, [first, second]) => { return [...a, {[keys[0]]: first, [keys[1]]: second}]; }, []); console.log(res);
 .as-console-wrapper{min-height: 100%;important: top:0}

 let dataKeys = ['foo', 'bar']; let dataValues = [ ['a', 'A'], ['b', 'B'] ]; let transformed = dataValues.reduce((result,item)=>{ result.push( dataKeys.reduce((r,dk,index)=>{ let o = {}; o[dk]= item[index]; return {...r, ...o} },{}) ) return result },[]); console.log(JSON.stringify(transformed,null,2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM