我有一个这样的对象数组:
[
{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/