我有这个数据:
[
{
"key": 111,
"studentInfo": [
{
"details": {
"calculated_fields": null,
"status": false
}
}
]
},
{
"key": 222,
"studentInfo": [
{
"details": {
"calculated_fields": null,
"status": false
}
}
]
},
{
"confidential": {
"data": {
"access_control": {
"private_data": null,
"users": []
}
},
"key": 111
}
},
{
"confidential": {
"data": {
"access_control": {
"private_data": null,
"users": []
}
},
"key": 222
}
}
]
现在我需要根据键合并数据。假设对象包含键“111”,则所有相关信息应显示为一个对象
示例输出:
[
{
"key": 111,
"studentInfo": [
{
"details": {
"calculated_fields": null,
"status": false
}
}
],
"confidential": {
"data": {
"access_control": {
"private_data": null,
"users": []
}
},
"key": 111
}
},
{
"key": 222,
"studentInfo": [
{
"details": {
"calculated_fields": null,
"status": false
}
}
],
"confidential": {
"data": {
"access_control": {
"private_data": null,
"users": []
}
},
"key": 222
}
}
]
**更新:**根据吴昊的回答,我得到以下输出
[
{
"key": 111,
"studentInfo": [
{
"details": {
"calculated_fields": null,
"status": false
}
}
]
},
{
"confidential": {
"data": {
"access_control": {
"private_data": null,
"users": []
}
},
"key": 222
}
}
]
完整代码:
const fs = require("fs");
var util = require('util');
const path = require("path");
const { ObjectFlags } = require('typescript');
const { join } = require('path');
const { stringify } = require('querystring');
const _ = require('lodash');
let rawdata = fs.readFileSync('./sample_data.json');
let jsondata = JSON.parse(rawdata);
let stud_records=[];
for (let i = 0; i < jsondata.records.length; i++) {
let obj = jsondata.records[i];
let key = obj.id;
let studentInfo = jsondata.records[i].data;
let data = {
studentInfo: [studentInfo],
key: key
};
stud_records.push(data);
}
let conf_records=[];
for (let i = 0; i < Object.values(jsondata.conf_data).length; i++) {
let obj = Object.values(jsondata.conf_data)[i];
let key = Object.values(jsondata.conf_data)[i].id;
let position = i+1;
let confidential = Object.values(jsondata.conf_data)[i];
let data = {
confidential: {
data:confidential,
key:key,
position: position
},
};
conf_records.push(data);
}
let joined_data= stud_records.concat(conf_records)
const merged = Object.values(joined_data.reduce((acc, cur) => {
const key = cur.confidential?.key ?? cur.key;
if (key)
acc[key] = { ...acc[key], ...cur };
return acc;
}, {}));
var log_file = fs.createWriteStream(__dirname + '/output.json', {flags : 'w'});
var log_stdout = process.stdout;
console.log = function(d) { //
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
console.log(JSON.stringify(merged, null, 2))
3条答案
按热度按时间cbwuti441#
根据您的结构,以下代码可以完成以下工作:
kcrjzv8t2#
下面是一个使用
Array.prototype.reduce
的解决方案:plicqrtu3#
我可以找出问题所在,这就是答案
不起作用:
工作时间: