I have object key value in below format.
{
"Code1": {
"char10": "ch1",
"number1": "1",
"text1": "txt1"
},
"Code2": {
"char2": "ch2",
"num2": "2"
},
"Code3": {
"text": "txt4"
}
}
Would like to convert to this format :
{
"Code1": [
{
"char10": "ch1",
"number1": "1",
"text1": "txt1"
}
],
"Code2": [
{
"char2": "ch2",
"num2": "2"
}
],
"Code3": [
{
"text": "txt4"
}
]
}
Managed to achieve to get somewhat similar response but not exact output which I am looking for.
Tried the below snippet but it returns diff format than expected.
Object.entries(payload).map((e) => ( { [e[0]]: e[1] } ))
Response with above snippet :
[
{
"Code1": {
"char10": "ch1",
"number1": "1",
"text1": "txt1"
}
},
{
"Code2": {
"char2": "ch2",
"num2": "2"
}
},
{
"Code3": {
"text": "txt4"
}
}
]
3
Answers
You could get all entries and map with wrapped values for a new object.
You can solve this problem by using
Object.entries()
withreduce()
to transform each entry into an array containing an object.Here’s how you can do it :
You will need to reduce the objects’s entries and for each key value pair, assign the key to the result object and supply it with the value wrapped inside of an array.
I wrote a reusable function below, that takes an optional
valueMapper
which can transform the value upon assignment to the resulting object.Of course, it can also be written using
Array.prototype.map
andObject.fromEntries
; instead ofArray.prototype.reduce
andObject.assign
. Either solution will work.