I know the title might be a bit confusing so I’ll try to explain visually. I’ve been struggling for days, I’ve searched all over but this is a very specific task.
I’m being provided with this API response:
{
"akash": {
"url": "127.0.0.1",
"count": 12
},
"aptos": {
"url": "127.0.0.2",
"count": 54
}
}
I need to convert it into a new object with this format:
{
"akash": {
"name": "akash",
"url": "127.0.0.1",
"count": 12
},
"aptos": {
"name": "aptos",
"url": "127.0.0.2",
"count": 54
}
}
If you can tell, now every subset has a new property "name" with the parent object’s key name as its value.
Another alternative would be to convert it into a proper array of objects, like this:
[
{
"name": "akash",
"url": "127.0.0.1",
"count": 12
},
{
"name": "aptos",
"url": "127.0.0.2",
"count": 54
}
]
2
Answers
You can iterate through the keys of the object.
Given you have an originalObject as your starting point, you can create a new object using the following code:
To create a list, the process is quite similar, but you’re generating a new array of objects and pushing the new values to the list:
https://tsplay.dev/WPB8ZN
This does work recursively
(note this adds
name
to existing objects, not creates new ones)