简体   繁体   English

有没有办法通过使用.forEach或.map而不是for-loop来解决这个问题?

[英]Is there a way to solve this problem by using .forEach or .map instead of for-loop?

I need to write a function that converts array elements within an array into objects. 我需要编写一个函数,将数组中的数组元素转换为对象。 Although I've figured out a way to solve the problem by using for-loop , I'm just wondering if there's more concise way to write up the solution by using methods such as forEach or map . 虽然我已经想出了一种通过使用for-loop解决问题的方法,但我只是想知道是否有更简洁的方法来编写解决方案,使用forEachmap等方法

The problem is... 问题是...

var array: [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

I need to convert the above array into something like this. 我需要将上面的数组转换成这样的东西。

[
  { firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk' },
  { firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager' }
];

The following is the code I've come up with by using a for-loop . 以下是我通过使用for-loop得出的代码。

function transformEmployeeData(array)
{  
  var output = [];

  for (var i = 0; i < array.length; i++)
  {
    var obj = {};

    for (var j = 0; j < array[i].length; j++)
    {
      obj[array[i][j][0]] = array[i][j][1];
    }

    output.push(obj);
  }

  return output;
}

Like I have mentioned above, it will be great if there's another way to solve the problem. 就像我上面提到的那样,如果有另一种方法可以解决问题,那将会很棒。

In some near future maybe you could use Object.fromEntries() . 在不久的将来,您可以使用Object.fromEntries() It is supported on some browsers version right now: Browser Compatibility : 它现在支持某些浏览器版本: 浏览器兼容性

 var arr = [ [ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk'] ], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ]; console.log(arr.map(Object.fromEntries)); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

You could map new objects by mapping the properties and join all properties to a single objects. 您可以通过映射属性来映射新对象,并将所有属性连接到单个对象。

 var data = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]], result = data.map(a => Object.assign(...a.map(([key, value]) => ({ [key]: value })))); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Using map and reduce. 使用map和reduce。

  var array = [ [['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ]; var transformed = array.map(a=> a.reduce((c, p) => {c[p[0]] = p[1]; return c;},{})); console.log(transformed); 

You can use map and reduce in tandem (map each element to the result of the reduce function, which transforms each element into a key/value pair): 您可以使用mapreduce串联(将每个元素映射到reduce函数的结果,将每个元素转换为键/值对):

 var array=[[['firstName','Joe'],['lastName','Blow'],['age',42],['role','clerk']],[['firstName','Mary'],['lastName','Jenkins'],['age',36],['role','manager']]]; const result = array.map(e => e.reduce((a, [k, v]) => ((a[k] = v) || 1) && a, {})) ; console.log(result); 

To achieve expected result, use below option of using map and forEach 要获得预期结果,请使用以下使用map和forEach的选项

 var array = [ [['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ]; console.log(array.map(val => { const result = {} val.forEach(v => { result[v[0]] = v[1] }) return result })) 

codepen - https://codepen.io/nagasai/pen/ROWmEX codepen - https://codepen.io/nagasai/pen/ROWmEX

yes, you can do it in one line. 是的,你可以在一行中完成。

 var array = [ [['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ]; const transformed = array.map(upperArr => upperArr.reduce((acc, itemArr) => { acc[itemArr[0]] = itemArr[1]; return acc;}, {})); console.log(transformed); 

Your function with map and forEach: 你的map和forEach函数:

function transformEmployeeData(array) {  
  return array.map(toObject => {
    const obj = {};
    toObject.forEach(([key, value]) => {
      obj[key] = value;
    });
    return obj;
  });
};

 var array = [ [['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ]; function transformEmployeeData(array) { return array.map(toObject => { const obj = {}; toObject.forEach(([key, value]) => { obj[key] = value; }); return obj; }); }; console.log(transformEmployeeData(array)); 

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

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