如果键在Array.map中已经存在,则将值推送到对象

时间:2018-12-02 21:22:01

标签: javascript arrays object array-map array-reduce

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

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)

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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。 / p>

示例:

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);

答案 2 :(得分:1)

["Poznan", "Poznań", "Gdańsk"].uniq 
=> ["Poznań", "Gdańsk"]