Reputation: 976
I have this json I need to format it in Typescript or java script. what would be better way to do.
var data = {
"value 1" : [
{
type : String,
Dicription : "abc"
},
{
type : int,
Dicription : "xyz"
},
{
type : String,
Dicription : "pqr"
},
]
"value 2" : [
{
type : String,
Dicription : "abc"
}
]
"value 3" : [
{
type : String,
Dicription : "abc"
},
{
type : int,
Dicription : "xyz"
}
}
Need Output like this
{
{
value : value1,
type : String,
Description : "abc"
},
{
value : value1,
type : int,
Dicription : "xyz"
},
{
value : value1,
type : String,
Dicription : "pqr"
},
{
value : value2,
type : String,
Description : "abc"
},
{
value : value3,
type : String,
Description : "abc"
},
{ value : value3,
type : int,
Description : "xyz"
}
}
I tried
var new = [];
Var values = Object.keys(data)
values.ForEach(Function(value){
new.push({
'value' : value })
});
and iterate it, but could not get desired output. I tried to flatten this but I got objects like {value : value , { type: String ,Description : abc}} What should I do to solve it
Upvotes: 0
Views: 1027
Reputation: 976
I get the keys and values separately and iterate though first object and create another object and push values in it.
So my solution for the problem is
var keys = Object.keys(data);
var values = Object.values(data);
var length = Object.values(data).length;
keys.ForEach(function (key, index){
values.ForEach(function (obj, i) {
if(index == i){
var innerValue = Object.values(obj);
for(i=0 ; i<=innerValue.length; i++)
{
new.push({
'value: key,
'type': innerValue[i].type,
'Description': innerValue[i].abc,
});
}
}
});
});```
Upvotes: 0
Reputation: 191976
Convert the object to an an array using Object.entries()
, and then flat map the entries to an array of objects:
const result = Object.entries(data) // get the entries of the object
.flatMap(([value, arr]) => // map and flatten the sub-arrays
arr.map(o => ({ // map each sub-array and combine with the value
value,
...o
}))
)
Upvotes: 2