Ashesh Khatri Ashesh Khatri -3 years ago 108
JSON Question

Want to convert array to duplicate key object in Node js

I Want to convert the array to duplicate key object in Nodejs. following is my array data,

{
"name" : "ashesh",
"address_data" : [
{
"city" : "Mumbai",
"pincode": "400097"
},
{
"city" : "Delhi",
"pincode": "1000001"
}
]
}


want to convert the array to the following object

{
"name" : "ashesh",
"address_data" : {
"address" : {
"city" : "Mumbai",
"pincode": "400097"
},
"address" : {
"city" : "Delhi",
"pincode": "1000001"
}
}
}


How can I achieve this structure in node js or in javascript. Please help me on this. I know this is not a valid JSON but want to convert above structure. I am stuck to achieve this structure.

Answer Source

If some third party still wants duplicate keys, instead create a string in the format of JSON object and send them. Remember this string won't be compliant to JSON and you won't be able to parse it.

var a = { 
"name" : "ashesh", 
"address_data" : [ 
{ 
"city" : "Mumbai", 
"pincode": "400097" 
}, 
{ 
"city" : "Delhi", 
"pincode": "1000001" 
} 
] 
} 

var b = `{"name": "${a.name}", "address_data": {`; 

a.address_data.forEach((x) => b = b + `"address": ${JSON.stringify(x)}`); 
b = b + "}}"; 
b = b.replace(/\}"address"/g, `},"address"`);
res.send(b);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download