最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to solve this problem by using .forEach or .map instead of for-loop? - Stack Overflow

programmeradmin5浏览0评论

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.

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 e up with by using a 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.

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.

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 e up with by using a 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.

Share Improve this question edited Apr 3, 2019 at 16:41 Shidersz 17.2k2 gold badges27 silver badges51 bronze badges asked Apr 3, 2019 at 15:15 DamagedcaseDamagedcase 754 bronze badges 4
  • I don't see any reason to do it another way if this way works well for you. If anything, your code right now is more readable than it would be using .map() or .forEach(). Is there a reason why you would want to do it another way? – Cristian C. Commented Apr 3, 2019 at 15:20
  • 2 Whenever you create an empty array, and iterate over something and add it to the array, you should probably use Array#map, but if your code works, it's not a good fit for this forum. Maybe codereview.stackexchange. Another suggestion, create a function that converts each line of you array into an object. – Ruan Mendes Commented Apr 3, 2019 at 15:20
  • I just started learning programming and learned about methods related to arrays recently. I just wanted apply what I've learned, but it didn't work out too well after hours of trying. I will avoid this kind of question in the the future. Thank you for your ments! – Damagedcase Commented Apr 3, 2019 at 15:25
  • There are enough answers here... I'd go with map reducer because you might have to reduce, also what happens if the array has the same key in separate indexes, reduce to me sounds correct – Jony-Y Commented Apr 3, 2019 at 15:28
Add a ment  | 

7 Answers 7

Reset to default 5

In some near future maybe you could use 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.

  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);

To achieve expected result, use below option of using map and 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

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);

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):

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);

Your function with map and 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));

发布评论

评论列表(0)

  1. 暂无评论