-->

nested json data minipulation for ngx datatable in

2019-09-19 14:23发布

问题:

I am trying to create a ngx datatable that creates columns dynamically from nested arrays, which with some research is not possible - so to achieve my desired result, I must flatten my nested arrays with the key / values that i need from each nested object into my parent object.

I need to manipulate my data so that my end result is a flat array and contains a line item for each object in the nested array earnings with 'abbreviation' being the key and 'amount' being the value..

I.e

[
{
employee_uuid:  978f37df-7e07-4118-be93-d82507ce5c46,
employee_code:  JB00024,
full_name:  Thulisile Sandra,
last_name:  Bhekiswayo
earnings:[{
    abbreviation: "NT HRS"
    amount: "45.00"
    money: false
    name: "Normal Time HRS"
    time: true
    unique: "7d783469-717e-408a-bc3c-93115cb632dd_true"
    uuid: "7d783469-717e-408a-bc3c-93115cb632dd"
    value: "45.00"
},
{
    abbreviation: "OT HRS"
    amount: "25.00"
    money: false
    name: "Normal Time HRS"
    time: true
    unique: "7d783469-717e-408a-bc3c-93115cb632dd_true"
    uuid: "7d783469-717e-408a-bc3c-93115cb632dd"
    value: "45.00"
}],
terminated  false
}
...
]

I'd like to look like this:

[
{
employee_uuid:  978f37df-7e07-4118-be93-d82507ce5c46,
employee_code:  JB00024,
full_name:  Thulisile Sandra,
last_name:  Bhekiswayo,

NT HRS: '45.00',
OT HRS, '25.00',

terminated:false
}
...
]

I am not sure how to go about this, I've tried reducing and map functions but no success.. I can add the nested arrays to the parent object with Object.assign but that takes the whole object, I need to create a new parameter from that object..

Any help would be hugely appreciated..

回答1:

You can use es6 destructuring for this, simply expose whatever properties you need and then "recompose" then into the object shape you want. For example:

return myEmployeeArray.map(employee => { 
const {earn } = employee
earn.map(field => field.abbreviation)
myDesiredObject = { fieldA: employee.abbreviation....fieldE:field.abbreviation} 
}

This would get you one of your nested fields