I am receving a response in javascript like below . I have given one example. There will be lots of different table_id coming with different values.
var a = [{
table_id: 11111111,
table_full_name: 'Jin',
total: '820.001',
paytable: '220.001',
name: 'Gross Profit',
code: 'LSGP'
},
{
table_id: 11111111,
table_full_name: 'Jin',
total: '820.001',
paytable: '300',
name: 'Profit',
code: 'LSTR'
},
{
table_id: 11111111,
table_full_name: 'Jin',
total: '820.001',
paytable: '300',
name: 'Volume',
code: 'OCVL'
}
]
let result = []
a.map(y => {
let index = result.findIndex(x => x.table_id === y.table_id)
if (index === -1) {
result.push({
table_id: y.table_id,
data: [y.name, y.code]
})
} else {
result[index].data.push(y.kpi_name)
}
})
console.log(result)
I am trying to create a json object like below . But its not working as required. Need some help
[
{
"table_full_name":"Jin",
"total" :"820.001",
"data":[
{
"name":"Gross Profit",
"code":"LSGP"
},
{
"name":"Profit",
"code":"LSTR"
},
{
"name":"Volume",
"code":"OCVL"
}
]
}
]
3
Answers
Use
Array::reduce()
to collect your data and some object destructuring to split your items into parts:You could use