javascript - 从对象数组中的属性创建对象

标签 javascript

我有一个这样的对象数组:

[
{id: 'id1', random: 'labels.prop1'},
{id: 'id2', random: 'labels.prop2'},
{id: 'id3', random: 'texts.anotherprop'}
]

有没有一种基于属性 random 从该数组生成对象的简短方法?我需要这个:

{
  texts: { 
       anotherprop: ''
  },
  labels: { 
       prop1: '', 
       prop2: '' 
  }
}

最佳答案

您可以使用 reduce() 两次来构建这个嵌套对象。

var data = [
{id: 'id1', random: 'labels.prop1'},
{id: 'id2', random: 'labels.prop2'},
{id: 'id3', random: 'texts.anotherprop'}
]

var result = data.reduce(function(r, o) {
  var arr = o.random.split('.')
  arr.reduce(function(a, b, i) {
    return (i != arr.length - 1) ? a[b] || (a[b] = {}) : a[b] = ''
  }, r)
  return r;
}, {})

console.log(result)

关于javascript - 从对象数组中的属性创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065701/

相关文章:

javascript - 使用 node.js 将文本文件中的正则表达式替换为文件内容

javascript - 带有 Set-Cookie Header 的 Safari/Chrome 的开发者控制台中不显示 Cookie,但在查看服务器日志时存在

javascript - 模态显示文本区域内容不是字符串

javascript - 为什么 ESLint 在将异步函数定义为现有对象的方法时会抛出解析错误以及如何防止它?

javascript - 通过自定义解析将 html 字符串渲染到 React 组件

javascript - 谷歌地图 API : error thrown when setting LatLng values

javascript - jQuery 延迟未按预期工作

javascript - 如何使用zombie测试<input type ="hidden">

javascript代码错误语法

javascript - GoJS中获取Panel的TextBlocks