0

Trying to get value from nodejs api call but i am getting like [object Object] So How to get values from an array object?

product.component.ts:

 this.sendDatatoInsertDb(this.selectedProduct.replace(/\s/g,''),JSON.stringify(this.registerForm.value));

 sendDatatoInsertDb(collection,collectionData) { 
    this.adminService.insertDataintoDb(collection,collectionData).subscribe(
      res => {  },
      err => {  console.log(err); }
    ); 
  }

this.registerForm.value is like

{
        "p_id": "C5",
        "product_name": "name",
        "product_weight": "250gm"

}

admin.service.ts:

 insertDataintoDb(collection,insertData){
    return this.http.get(environment.apiBaseUrl + '/insertData?collection='+collection+'&collectionData='+insertData);
  }

product.controller.js:

module.exports.insertData = (req, res, next) => { 
    let collectionName = req.query.collection; 
    let collectionData = req.query.collectionData;
        console.log(collectionData); //Getting [object Object]
        console.log(collectionData.p_id); //Getting undefined
        console.log(collectionData.product_name); //Getting undefined
        console.log(collectionData.product_weight);  //Getting undefined
}
4
  • JSON.stringfy(object) try this Commented May 16, 2020 at 9:54
  • @SaadSohail : Getting error : TypeError: JSON.stringfy is not a function Commented May 16, 2020 at 9:58
  • ur question is not clear. please add proper details Commented May 16, 2020 at 9:59
  • let response = JSON.stringfy(collectionData) object is the response that you are getting from api Commented May 16, 2020 at 10:00

1 Answer 1

1

You have to parse the string to get your object back using JSON.parse.

module.exports.insertData = (req, res, next) => { 
    let collectionName = req.query.collection; 
    let collectionData = req.query.collectionData;
    let collectionDataJSON = JSON.parse(collectionData);
    console.log(collectionDataJSON.p_id);

}
Sign up to request clarification or add additional context in comments.

21 Comments

Getting error :TypeError: collectionData.each is not a function
I update the code to forEach. Forgot that each is not a javascript method. My bad lol @KavithaK
Getting error: TypeError: collectionData.forEach is not a function
I am suspecting that your array is return as a string. You might have to parse it first. Replace let collectionData = req.query.collectionData; with let collectionData = JSON.parse(req.query.collectionData);. To really help you i will need to know the type of collectionData but i think this will help
Getting error: SyntaxError: Unexpected token o in JSON at position 1
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.