I have an Javascript object object like the following:
"xx2b": {
"county": "Baringo",
"town": "Kabarnet",
"saccoRegistration": "BO2/08/009",
"saccoName": "Baringo2"
},
"QQDa": {
"saccoRegistration": "Ba/09/009",
"town": "Mogotio",
"county": "Baringo",
"saccoName": "Baringo1"
}
}
How do I assign the Object Keys also to be values within the objects?
The expected outcome is as illustrated below:
{
"xx2b": {
"id": "xx2b",
"county": "Baringo",
"town": "Kabarnet",
"saccoRegistration": "BO2/08/009",
"saccoName": "Baringo2"
},
"QQDa": {
"id":"QQDa",
"saccoRegistration": "Ba/09/009",
"town": "Mogotio",
"county": "Baringo",
"saccoName": "Baringo1"
}
}
CodePudding user response:
You can use forEach
to iterate the object keys and add a new property to each nested object:
const data = {
"xx2b": {
"county": "Baringo",
"town": "Kabarnet",
"saccoRegistration": "BO2/08/009",
"saccoName": "Baringo2"
},
"QQDa": {
"saccoRegistration": "Ba/09/009",
"town": "Mogotio",
"county": "Baringo",
"saccoName": "Baringo1"
}
}
Object.keys(data).forEach(k => data[k].id = k)
console.log(data)