From a database result. I got a response like
[
{
id: 11544,
emp_code: "DF",
date_received: "2000-10-18",
closed_ind: "C",
declined: null,
create_date: "2000-10-18",
billing_rate: null,
emp1sk: 10151,
emp2sk: 10151,
emp3sk: 10052,
emp1name: 'efraim',
emp2name: 'andrea',
emp3name: 'monique',
},
{
....},
...........
]
with this record how I can make a array of object like
[
{
id: 11544,
emp_code: "DF",
date_received: "2000-10-18",
closed_ind: "C",
declined: null,
create_date: "2000-10-18",
billing_rate: null,
emp: [{
id: 10151,
name: 'efraim'
}, {
id: 10151,
name: 'andrea'
}, {
id: 10052,
name: 'monique'
}]
},
, {
....},
...........
]
i can not change the database nor the getting response. how i can make it and also the employee is not limited to the it can be anything. how i can do that
CodePudding user response:
You can first get the count of emp_sk values and then use a for loop to insert sk and name in emp array and insert the rest of key-value pair as it is
const q = [
{
id: 11544,
emp_code: "DF",
date_received: "2000-10-18",
closed_ind: "C",
declined: null,
create_date: "2000-10-18",
billing_rate: null,
emp1sk: 10151,
emp2sk: 10151,
emp3sk: 10052,
emp1name: 'efraim',
emp2name: 'andrea',
emp3name: 'monique'
},
{
id: 11545,
emp_code: "DS",
date_received: "2000-10-18",
closed_ind: "C",
declined: null,
create_date: "2000-10-18",
billing_rate: null,
emp1sk: 10151,
emp2sk: 10151,
emp1name: 'efraim',
emp2name: 'andrea'
}
]
console.log(
q.map((e) => {
const length = Object.keys(e).filter((key) => key.match('emp[0-9] sk')).length;
let emp = [];
for(let i=1; i<=length; i ) {
emp.push({id: e[`emp${i}sk`], name: e[`emp${i}name`]})
}
let ans = {
id: e['id'],
emp_code: e['emp_code'],
date_received: e['date_received'],
closed_ind: e['closed_ind'],
declined: e['declined'],
create_date: e['create_date'],
billing_rate: e['billing_rate']
}
return {...ans, emp};
})
)
