如何使用promises来对嵌套的json进行非规范化?

时间:2016-04-18 11:19:27

标签: javascript json bluebird

我试图压扁和反规范化数据。我不明白如何使用承诺来实现这一目标。我错过了什么?

我得到的结果是:

Bob,Nancy
Bob,Nancy

但我想得到:

Bob,Sue
Bob,Nancy

代码:

var Promise = require('bluebird');

var jsonData = {
  "Parents": [{
    "Name": "Bob",
    "AllChildren": [{
      "Name": "Sue"
    }, {
      "Name": "Nancy"
    }]
  }, {
    "Name": "Ron",
    "AllChildren": [{
      "Name": "Betty"
    }, {
      "Name": "Paula"
    }]
  }, {
    "Name": "Peter",
    "AllChildren": [{
      "Name": "Mary"
    }, {
      "Name": "Sally"
    }]
  }]
};


var promises = Promise.map(jsonData.Parents, function(parent) {
  var record = {};
  record.ParentName = parent.Name;
  var allRecords = Promise.map(parent.AllChildren, function(child) {
    var fullRecord = record;
    fullRecord.ChildName = child.Name;
    return fullRecord;
  });
  return Promise.all(allRecords);
});

console.log(JSON.stringify(promises, null, 2));

2 个答案:

答案 0 :(得分:1)

你在这里缺少的是,承诺是承诺的价值和#34;这将在你"然后"他们。在promise链中返回的值/ promise遍历它并由下一个处理程序提取。

更新:在展平中使用concat

更改您的实施方式:

return Promise.map(jsonData.Parents, function(parent) {
  return Promise.map(parent.AllChildren, function(child) {
    return { ParentName: parent.Name, ChildName: child.Name };
  });
})
.reduce(function (accumulator, item){
  // Flatten the inner arrays
  return accumulator.concat(item);
}, [])
.then(function (flattened) {
  console.log(JSON.stringify(flattened, null, 2));
});

答案 1 :(得分:0)

不使用承诺你可以尝试:

jsonData.Parents.reduce(
    function(p, c){
        var children = c.AllChildren.map(
                         function (item){
                           return {ParentName:c.Name, ChildName: item.Name};
                         });
        return p.concat(children);
    }, []);