如何使用promise来反规范化嵌套json

How to use promises to denormalize nested json?

本文关键字:规范化 嵌套 json 何使用 promise      更新时间:2023-09-26

我正在尝试对数据进行展平和反规范化。我不知道如何使用承诺来实现这一点。我错过了什么?

我得到的结果是:

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));

这里缺少的是,promise是"承诺的值",一旦"然后"它们就会被评估。promise链中返回的值/promise遍历它,并由next-then处理程序获取。

更新:在压平中使用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));
});

如果不使用promise,您可以尝试:

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