I'm using external API to make an SQL query for a user. As a result i get matching Entity but as a set of fields, lookin like this:
[
{ IsNull: false, Name: 'Key', Value: '897', Values: null },
{ IsNull: false, Name: 'FirstName', Value: 'User', Values: null },
{ IsNull: false, Name: 'LastName', Value: 'Portal', Values: null },
{
IsNull: false,
Name: 'Email',
Value: '[email protected]',
Values: null
},
{ IsNull: true, Name: 'Salutation', Value: null, Values: null },
{ IsNull: false, Name: 'Type', Value: '2', Values: null },
{
IsNull: false,
Name: 'LastLoggedDate',
Value: '2022-12-01 15:24:03',
Values: null
}
]
How to transform this response to end with simple object { email: 'some@email', firstName: 'User' lastName: 'Portal' } ??
I ended up with solution like this (below) but i believe there's some easiest way to do that, especially with more fields
let userRawEntity = queryResult.data.Entities[0].Fields;
const userEmail = userRawEntity.filter((obj) => { return obj.Name === 'Email' });
const userFirstName = userRawEntity.filter((obj) => { return obj.Name === 'FirstName' });
const userLastName = userRawEntity.filter((obj) => { return obj.Name === 'LastName' });
return { email: userEmail[0].Value, firstName: userFirstName[0].Value, lastName: userLastName[0].Value };
CodePudding user response:
As a starting point, I would transform that entire array into an object as follows:
let dataTransformed: {[key: string]: string | null} = {}
data.forEach(d => {
dataTransformed[d.Name] = d.Value
})
Which will give you a nicer looking object as follows:
{
"Key": "897",
"FirstName": "User",
"LastName": "Portal",
"Email": "[email protected]",
"Salutation": null,
"Type": "2",
"LastLoggedDate": "2022-12-01 15:24:03"
}
You now have a familiar object with which to work with. From here, you can strip out the entries you don't want. Note, you may want to do further work in that array transformation such as checking for null values, changing keys to camel case, etc...
CodePudding user response:
Another approach using lodash
_.mapValues(_.keyBy(data, "Name"), o => o.Value || o.Values);