0
votes

I'm working with a simple reactive form and after entering firstName, lastName and Answer I'm able to print out the values in the console like this:

{firstName: "Peter", lastName: "Smith", answer: {…}}

However, I want to print out the value of answer as a simple string and NOT an object.

Expected Result:

{firstName:"Peter", lastName:"Smith", answer:'Yes'}

Does anyone have any idea how to make this happen?

Here's my code: LIVE DEMO

3
You could always console.log this instead: Object.assign({}, this.searchform.value, { answer: this.searchform.value.answer.label }) - Daniel W Strimpel
You can literally copy that code in your stackblitz as is to see it... stackblitz.com/edit/angular-rvpmjk - Daniel W Strimpel
@DanielWStrimpel thanks a lot bro! - Devmix
JSON.stringify(this.searchform.value); try this or you can directly use Json pipe in html like {{ searchform.value | json }} - Nitin Walia

3 Answers

0
votes

Remove the optionLabel="label" property from your p-dropdown, and intialise the answers object with a value, and a label:

this.answers = [
  { label: 'Yes', value: 'Yes' },
  { label: 'No', value: 'No' },
];

This will now print in your expected format.

Here is a fork of the Stackblitz

0
votes

How about this?

const newObj = {
   'firstName': this.searchform.value.firstName,
   'lastName': this.searchform.value.lastName,
   'answer': this.searchform.value.answer.label,
};
console.log(newObj);
-1
votes

This happens because you have an array inside and you gotta access the value of the array

console.log(this.searchform.value.firstName);
console.log(this.searchform.value.lastName);
console.log(this.searchform.value.answer.label);