1

我有一个看起来像这样的数组:

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)

4

3 回答 3

3

您可以使用一个Array.reduce和一个来执行此操作array destructuring以获得key/value组合:

let movies = [ 'terminator.1', 'terminator.2', 'terminator.3', 'harry-potter.1', 'harry-potter.3', 'harry-potter.2', 'star-wars.1' ]

const result = movies.reduce((r,c) => {
  let [k,v] = c.split('.')
  r[k] = [...r[k] || [], +v]
  return r
},{})

console.log(result)

于 2018-12-02T21:28:34.720 回答
1

这是一份工作Array#reduce,而不是Array#map

let t = movies.reduce((acc, movie) => {             // for each movie in movies
   let [name, number] = movie.split('.');           // split the movie by "." and store the first part in name and the second in number
   if(acc[name]) {                                  // if the accumulator already has an entry for this movie name
      acc[name].push(number);                       // then push this movie number into that entry's array
   } else {                                         // otherwise
      acc[name] = [number];                         // create an entry for this movie name that initially contains this movie number
   }
   return acc;
}, Object.create(null));                            // Object.create(null) is better than just {} as it creates a prototypeless object which means we can do if(acc[name]) safely

注意:如果要将数字强制转换为实际数字而不是将它们保留为字符串,则使用一元+来隐式转换它们:+number.

例子:

let movies = [ 'terminator.1', 'terminator.2', 'terminator.3', 'harry-potter.1', 'harry-potter.3', 'harry-potter.2', 'star-wars.1' ];

let t = movies.reduce((acc, movie) => {
   let [name, number] = movie.split(".");
   if(acc[name]) {
      acc[name].push(number);
   } else {
      acc[name] = [number];
   }
   return acc;
}, Object.create(null));

console.log(t);

于 2018-12-02T21:26:52.450 回答
1

const movies = ['terminator.1', 'terminator.2', 'terminator.3', 'harry-potter.1', 'harry-potter.3', 'harry-potter.2', 'star-wars.1']

const moviesMap = {}

movies.forEach(data => {
  const [title, id] = data.split('.')
  if (moviesMap[title]) {
    moviesMap[title].push(id)
  } else {
    moviesMap[title] = [id]
  }
})

console.log(moviesMap)

于 2018-12-02T21:45:25.067 回答