如何使用promise来反规范化嵌套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));
这里缺少的是,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);
}, []);
相关文章:
- 用嵌套函数和默认函数定义函数
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 可以简化嵌套的延迟Q Promises解析吗
- 用于搜索的聚合物嵌套绑定
- 如何使用javascript获取嵌套对象中所有子对象的单个属性
- d3中堆栈函数和嵌套函数之间的差异
- 如何打印嵌套对象的所有值
- JavaScript 中的嵌套函数和 “this” 关键字
- 设置嵌套对象属性的更好方法
- querySelector/getElementByClassName嵌套项的顺序
- 猫鼬在特定记录中查找嵌套记录
- 访问嵌套JSON对象的键,其中键是动态的
- D3嵌套组作为x轴
- Ionic和angularjs嵌套步骤应用程序
- 从多维嵌套json数组创建下拉列表
- 默认情况下折叠和展开嵌套列表
- 嵌套对象结构
- 如何使用promise来反规范化嵌套json
- 使用jQuery或JavaScript规范化嵌套块
- 更新react redux中的深层嵌套状态(规范化)