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 offorEach
– 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
4 Answers
Reset to default 6Consider 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
版权声明:本文标题:javascript - Return object from forEach? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743887890a2556392.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论