【发布时间】:2019-05-04 05:09:37
【问题描述】:
我有一个如下所示的数组:
let movies = [
'terminator.1',
'terminator.2',
'terminator.3',
'harry-potter.1',
'harry-potter.3',
'harry-potter.2',
'star-wars.1'
]
我想要一个这样的对象:
{
"terminator": [1,2,3],
"harry-potter": [1,2,3],
"star-wars": [1]
}
到目前为止,我能够拥有这样的对象
{
{ terminator: [ '1' ] },
{ terminator: [ '2' ] },
{ terminator: [ '3' ] },
{ 'harry-potter': [ '1' ] },
{ 'harry-potter': [ '3' ] },
{ 'harry-potter': [ '2' ] },
{ 'star-wars': [ '1' ] }
}
我想知道是否有一种方法可以在生成对象时检查 Array.map 是否已经存在某个键,以及是否可以将值推送到相应的数组而不是创建一个新的键值对。
这是我目前用于解决方案的代码。提前致谢。
let movies = [
'terminator.1',
'terminator.2',
'terminator.3',
'harry-potter.1',
'harry-potter.3',
'harry-potter.2',
'star-wars.1'
]
let t = movies.map(m => {
let [name, number] = [m.split('.')[0],m.split('.')[1]]
return {[name]: [number]}
})
console.log(t)
【问题讨论】:
标签: javascript arrays object array-map array-reduce