我有三个JSON文件。我的目标是通过以某种方式组合来自它们的数据来创建一个新的。
充其量我认为我有正确的逻辑和语法可以合并数据(如果有误,请更正),但是:
return
的含义。第一个障碍是,至少当我记录该函数的调用结果时,它返回 undefined 。有什么问题吗?
即使我获得了通过,代码中的最后两行是否也完全正确地写入了文件?
我尝试了三种变体,唯一的不同是我现在和将来不会回来。
代码:
var fs = require('fs');
const safeJsonStringify = require('safe-json-stringify');
var asanaProjects = require("C:/Users/GabrielRivera/asana/Asana Projects.json");
var asanaTasks = require("C:/Users/GabrielRivera/asana/Asana Tasks.json");
var asanaAttachments = require("C:/Users/GabrielRivera/asana/Asana Attachments.json");
function buildNewJSON() {
return asanaProjects.map(project => {
project.attachments = []
asanaTasks.map(task => {
if(project.items.includes(task.__object_id)){
asanaAttachments.map(attachment => {
if(task.attachments.includes(attachment.__object_id)){
project.attachments.push(attachment)
return project
}
})
}
})
})
}
console.log(buildNewJSON())
var asanaData = safeJsonStringify(buildNewJSON());
fs.writeFile("asanaData.json", asanaData);
生成的JSON文件: [null,null,null ...]
代码:
function buildNewJSON() {
return asanaProjects.map(project => {
project.attachments = []
asanaTasks.map(task => {
if(project.items.includes(task.__object_id)){
asanaAttachments.map(attachment => {
if(task.attachments.includes(attachment.__object_id)){
project.attachments.push(attachment)
}
})
}
})
})
}
console.log(buildNewJSON())
var asanaData = safeJsonStringify(buildNewJSON());
fs.writeFile("asanaData.json", asanaData);
生成的JSON文件: [null,null,null ...]
代码:
function buildNewJSON() {
asanaProjects.map(project => {
project.attachments = []
asanaTasks.map(task => {
if(project.items.includes(task.__object_id)){
asanaAttachments.map(attachment => {
if(task.attachments.includes(attachment.__object_id)){
project.attachments.push(attachment)
return project
}
})
}
})
})
}
console.log(buildNewJSON())
var asanaData = safeJsonStringify(buildNewJSON());
fs.writeFile("asanaData.json", asanaData);
生成的JSON文件:未定义
答案 0 :(得分:0)
更新您的buildNewJson
方法。
function buildNewJSON() {
return asanaProjects.reduce(function(output,project){
project.attachments = [];
asanaTasks = asanaTasks.reduce(function(tasks,task){
if(project.items.includes(task.__object_id)){
asanaAttachments = asanaAttachments.reduce(function(attachments,attachment){
if(task.attachments.includes(attachment.__object_id)){
project.attachments.push(attachment);
}
attachments.push(attachment);
return attachments;
},[]);
}
tasks.push(task);
return tasks;
},[]);
output.push(project);
return output;
},[]);
}