Reputation: 63
I have json data in fields that are split across rows. I want to have all these fields in a single row. I would like to write a javascript function that takes the original input and produces the output. I am very new to javascript. I would like to do this in a dynamic way so that I don't have to explicitly name the new fields -- rather iterate through all the fields in each row one by one and append them to a new row, with the same names/values. Thanks in advance.
Starting json:
[
{
"name": "Sara Smith",
"dob": "19831002"
},
{
"title": "director",
"emails": [
"[email protected]",
"[email protected]"
]
},
{
"phones": [
{
"type": "home",
"number": "3452345432"
},
{
"type": "work",
"number": "3452345343"
}
]
}
]
Desired end state json:
[
{
"name": "Sara Smith",
"dob": "19831002"
"title": "director",
"emails": [
"[email protected]",
"[email protected]"
]
"phones": [
{
"type": "home",
"number": "3452345432"
},
{
"type": "work",
"number": "3452345343"
}
]
}
]
Upvotes: 0
Views: 133
Reputation: 17190
One possible solution is to use Array.reduce() in combination with Object.assign():
const input = [
{"name": "Sara Smith", "dob": "19831002"},
{
"title": "director",
"emails": ["[email protected]", "[email protected]"]
},
{
"phones": [
{"type": "home", "number": "3452345432"},
{"type": "work", "number": "3452345343"}
]
}
];
let output = input.reduce((acc, curr) =>
{
Object.assign(acc[0], curr);
return acc;
}, [{}]);
console.log(output);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Upvotes: 0
Reputation: 44125
Use reduce
:
const startJSON = [{
"name": "Sara Smith",
"dob": "19831002"
},
{
"title": "director",
"emails": [
"[email protected]",
"[email protected]"
]
},
{
"phones": [{
"type": "home",
"number": "3452345432"
},
{
"type": "work",
"number": "3452345343"
}
]
}
];
const endJSON = [startJSON.reduce((acc, curr) => ({ ...acc, ...curr }))];
console.log(endJSON);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Upvotes: 1