I have a variable, FirstName and LastName, I want to add it to the return response,
note the FirstName and LastName are not present/available on table Student.
let result = await Student.get(id)
let FirstName = "Paul"
let LastName = "Richard"
results = {
...result,
FirstName: params.body.FirstName,
LastName: params.body.LastName
}
current result
{
0:{
"Teacher": "adasfsafag",
"Subject": "asdafdfhd",
},
"FirstName": "Paul",
"LastName": "Richard"
}
what i want is
{
"Teacher": "adasfsafag",
"Subject": "asdafdfhd",
"FirstName": "Paul",
"LastName": "Richard"
}
when I didnt add the FirstName and LastName in the respone
this is the result
{
"data": {
"School":{
"Teacher": "adasfsafag",
"Subject": "asdafdfhd"
}
}
}
CodePudding user response:
Destructure the first element of the array. You might want some bounds checking before doing this...
if (result.length) {
results = {
...result[0],
FirstName: params.body.FirstName,
LastName: params.body.LastName
}
// or
results2 = {
Teacher:result[0].Teacher,
Subject:result[0].Subject,
FirstName: params.body.FirstName,
LastName: params.body.LastName
}
}
CodePudding user response:
You need to spread the nested node School
this way:
const result = {
"data": {
"School":{
"Teacher": "adasfsafag",
"Subject": "asdafdfhd",
}
}
};
const FirstName = "Paul";
const LastName = "Richard";
results = { ...result.data.School, FirstName, LastName };
console.log(results);
.as-console-wrapper { max-height: 100% !important; top: 0 }