What is the most efficient method to "flatten" a JSON array of objects using only JavaScript or Lodash?
Consider this sample array
[
{
"name": "Mat",
"age": "18",
"studies": [
{
"subject": "English",
"mark": 5
},
{
"subject": "Maths",
"mark": 4
}
],
},
{
"name": "Alice",
"age": 20,
"city": "New York"
}
]
Desired output:
[
{
"name": "Mat",
"age": "18",
"subject": "English",
"mark": 5
},
{
"name": "Mat",
"age": "18",
"subject": "Maths",
"mark": 4
},
{
"name": "Alice",
"age": 20,
"city": "New York"
}
]
Here's an edited working code snippet:
rows.forEach(row => {
let newRow = {}
_.forOwn(row, (value, key) => {
value.forEach(item => {
_.forOwn(item, (value, key) => {
newRow[key] = value
})
})
} else {
newRow[key] = value
}
})
})
The current code doesn't include first-level properties like name
, which was sufficient for previous requirements. However, now all properties except those under fields like studies
are needed.