如何使用承诺对嵌套 json 进行非规范化?
How to use promises to denormalize nested json?
我正在尝试对数据进行扁平化和非规范化处理。我不明白如何使用承诺来实现这一点。我错过了什么?
我得到的结果是:
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));
不使用 promises 你可以试试:
jsonData.Parents.reduce(
function(p, c){
var children = c.AllChildren.map(
function (item){
return {ParentName:c.Name, ChildName: item.Name};
});
return p.concat(children);
}, []);
您在这里缺少的是,承诺 "promised values" 将在您 "then" 后立即对其进行评估。在 promise 链中返回的 values/promises 遍历它并由下一个 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));
});
我正在尝试对数据进行扁平化和非规范化处理。我不明白如何使用承诺来实现这一点。我错过了什么?
我得到的结果是:
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));
不使用 promises 你可以试试:
jsonData.Parents.reduce(
function(p, c){
var children = c.AllChildren.map(
function (item){
return {ParentName:c.Name, ChildName: item.Name};
});
return p.concat(children);
}, []);
您在这里缺少的是,承诺 "promised values" 将在您 "then" 后立即对其进行评估。在 promise 链中返回的 values/promises 遍历它并由下一个 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));
});