将键值对的数组转换为一个对象

时间:2018-06-03 12:05:16

标签: javascript node.js

如何将以下数组的键值对转换为单个对象。

       arr = [ { '/a': { component: [Function] },
            '/a/1': { component: [Function] },
            '/a/2': { component: [Function] },
            '/a/2/1': { component: [Function] },
            '/ab/2/1': { component: [Function] },
            '/b/1': { component: [Function] },
            '/b/login/register': { component: [Function] } },

             { '/ac': { component: [Function] },
            '/a/1': { component: [Function] } },
            ]

将上述对象转换为

   obj = { '/a': { component: [Function] },
        '/a/1': { component: [Function] },
        '/a/2': { component: [Function] },
        '/a/2/1': { component: [Function] },
        '/ab/2/1': { component: [Function] },
        '/b/1': { component: [Function] },
        '/b/login/register': { component: [Function] } } 

更新

当存在重复键时,我们希望在将数组对象合并到对象时记录警告。

1 个答案:

答案 0 :(得分:0)

const obj = {};

for(let row of arr) { 
  for(let key in row) {
    if(key === 'component') {
      continue
    }
    if(obj[key]) {
      console.warn('duplicate key', key)
    }
    obj[key] = row[key]
  }
}

console.log(obj)