Yuno
Yuno

Reputation: 109

Nodejs override or add another return response

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"
      }
  }
}

Upvotes: 1

Views: 46

Answers (2)

A1exandr Belan
A1exandr Belan

Reputation: 4780

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 }

Upvotes: 1

Steven Spungin
Steven Spungin

Reputation: 29101

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
 }
}

Upvotes: 0

Related Questions