[英]Map function to build an array from filtered object
I'm trying to get my head around map functions currently without much success.我正在尝试了解 map 函数,但目前没有太大成功。
I currently have a list of objects and am trying to remap to a new object using the map function to return a map indexed by the created property with a list of wooids.我目前有一个对象列表,正在尝试使用 map function 重新映射到新的 object 以返回由创建的属性索引的 map 和一个 wooids 列表。
Having written my map function, I only seem to be returning the last time.写了我的map function,我好像只是最后一次回来。
const variants = [ { created: '2022-03-06', hashname: 'c78ba80402290724609a5e98c369c90984494152', hashobject: '80864e6329d5e305a512ace872ad7d56a3f41095', hashparent: '19c5d50ddddeb7c9a92469df78c47d9d611f1599', action: 'added', wooid: 7288 }, { created: '2022-03-06', hashname: 'c78ba80402290724609a5e98c369c90984494152', hashobject: '80864e6329d5e305a512ace872ad7d56a3f41095', hashparent: '19c5d50ddddeb7c9a92469df78c47d9d611f1599', action: 'added', wooid: 7289 } ] const res = Object.fromEntries(variants.map(k => [k.created, [k.wooid]])) console.log(res)
{ '2022-03-06': [ 7289, 7288 ] }
Desired output:所需的 output:
{ '2022-03-06': [ 7289, 7288 ] }
Any help would be greatly appreciated as I'm unsure how to dynamically populate the array to include all other entires (6 in total).任何帮助将不胜感激,因为我不确定如何动态填充数组以包含所有其他整体(总共 6 个)。
Use Array.prototype.reduce() to build up your object. Check if you already have a key for each created
value and if not, create an empty array.使用Array.prototype.reduce()构建您的 object。检查您是否已经为每个
created
的值创建一个键,如果没有,则创建一个空数组。 Then append the wooid
value然后是 append 的
wooid
值
const variants = [{"created":"2022-03-06","hashname":"c78ba80402290724609a5e98c369c90984494152","hashobject":"80864e6329d5e305a512ace872ad7d56a3f41095","hashparent":"19c5d50ddddeb7c9a92469df78c47d9d611f1599","action":"added","wooid":7288},{"created":"2022-03-06","hashname":"c78ba80402290724609a5e98c369c90984494152","hashobject":"80864e6329d5e305a512ace872ad7d56a3f41095","hashparent":"19c5d50ddddeb7c9a92469df78c47d9d611f1599","action":"added","wooid":7289}] const res = variants.reduce((acc, { created, wooid }) => ({...acc, [ created ]: [...acc[created]?? [], // init to an empty array if unset wooid ] }), {}) console.log(res)
This will collect wooid
values by created
in the order they appear in the original data.这将按照它们在原始数据中出现的顺序
created
并收集wooid
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.