I have this data:
[
{
"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
}
}
]
Now I need to merge the data based on the key. For suppose if the objects contain the key"111" all the related info should be displayed as one obj
Example output:
[
{
"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
}
}
]
UPDATE:
Based on Hao Wu answer I get the following output
[
{
"key": 111,
"studentInfo": [
{
"details": {
"calculated_fields": null,
"status": false
}
}
]
},
{
"confidential": {
"data": {
"access_control": {
"private_data": null,
"users": []
}
},
"key": 222
}
}
]
Entire Code:
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))
2
Answers
Based on your structure, this code can do the job:
Here’s a solution using
Array.prototype.reduce
: