多级对象到单级对象

时间:2015-07-21 13:03:27

标签: javascript underscore.js

我正在尝试将复杂的对象数组文档映射到单个级别的数组。例如..

[{
    name: 'birds',
    references: [{ name: 'owl', value: 20 },
                 { name: 'sparrow', value: 23 }],
    identified: { created: '2014-02-02' }
}, {
    name: 'animals',
    references: [{ name: 'cat', value: 20 },
                 { name: 'deer', value: 23 }],
    identified: { created: '2014-02-02' }
}]

目标是无论复杂性如何,都将数组变成这样的东西

[{name: 'birds', references-owl: 20, references-sparrow: 23, identified-created: '2014-02-02'},
 {name: 'animals', references-cat: 20, references-deer: 23, identified-created: '2014-02-02'}]

基本上,如果循环遍历数组中的每个项目,然后循环遍历每个属性。

如果属性是一个数组,则将属性添加到父对象,其中键由数组中的name属性和父键值组成,例如' references-owl'和物业的价值。除第一级之外,所有其他数组对象都可以忽略。

如果属性是对象,则在键的前面加上parent属性,并将其添加到父对象。如果存在子数组,请重复上述步骤。

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

.map().reduce()的组合正如您所需:

var data = [{
  name: 'birds',
  references: [{ name: 'owl', value: 20 },
               { name: 'sparrow', value: 23 }],
  identified: { created: '2014-02-02' }
}, {
  name: 'animals',
  references: [{ name: 'cat', value: 20 },
               { name: 'deer', value: 23 }],
  identified: { created: '2014-02-02' }
}];

var result = data.map(function(row){  // For each row in data.
  // Set the static data in the result row
  var reference = { name: row.name, 'identified-created': row.identified.created };
  
  // Iterate over `row.references`, and add the current reference to the result.
  row.references.reduce(function(previous, current){
    previous['reference-' + current.name] = current.value;
    return previous;
  }, reference);
  
  return reference;
});

console.log(result);