admin管理员组

文章数量:1353252

Is it possible to construct an object from the return of a forEach? How I'm doing:

const data = {}
object.rules.forEach(rule => {
  data[rule.name] = { body: [], type: rule.type }
})

How I would like to do:

const data = object.rules.forEach(rule => {
  data[rule.name] = { body: [], type: rule.type }
})

Is it possible to construct an object from the return of a forEach? How I'm doing:

const data = {}
object.rules.forEach(rule => {
  data[rule.name] = { body: [], type: rule.type }
})

How I would like to do:

const data = object.rules.forEach(rule => {
  data[rule.name] = { body: [], type: rule.type }
})
Share Improve this question edited Jan 6, 2018 at 17:20 TGrif 5,9419 gold badges35 silver badges55 bronze badges asked Jan 6, 2018 at 15:36 FXuxFXux 4357 silver badges16 bronze badges 4
  • Just use reduce instead of forEach – nem035 Commented Jan 6, 2018 at 15:41
  • forEach() never provides a return. Try for...in – zer00ne Commented Jan 6, 2018 at 15:41
  • Isnt map for arrays? – FXux Commented Jan 6, 2018 at 15:41
  • IUPI! With reduce is working! I didn't know that I could use reduce like that!. I will up all questions, but accept the oldest. – FXux Commented Jan 6, 2018 at 15:45
Add a ment  | 

4 Answers 4

Reset to default 6

Consider using Array.reduce

const data = object.rules.reduce((obj, rule) => {
  obj[rule.name] = { body: [], type: rule.type }
  return obj;
}, {})

and shorter version

const data = object.rules.reduce((obj, rule) => Object.assign({}, obj, {[rule.name]:{ body: [], type: rule.type } }), {})

Whenever you want to convert an array into another structure that isn't an array, reduction is your friend.

console.log(
  ['a', 'b', 'c'].reduce((obj, char, index) => {
    obj[char] = index;
    return obj;
  }, {})
)

No you can't use forEach for this purpose. Calling forEach on an array object applies the callback function you supply to forEach at each element in the array object.

You could use reduce for this purpose, which

applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value

const data = object.rules.reduce(function(obj, rule) {
    obj[rule.name] = { body: [], type: rule.type }
    return obj;
}, {});

For a detailed explanation about this method please have a look here.

You could use Object.assign with a spread syntax ... and Array#map for single objects.

const data = Object.assign(...object.rules.map(
    rule => ({ [rule.name]: { body: [], type: rule.type } }))
);

with destructuring assignment for name and type and short hand property

const data = Object.assign(...object.rules.map(
    ({ name, type }) => ({ [name]: { body: [], type } }))
);

本文标签: javascriptReturn object from forEachStack Overflow