【问题标题】:How to print single string and not object?如何打印单个字符串而不是对象?
【发布时间】:2018-11-13 22:02:57
【问题描述】:

我正在使用一个简单的响应式表单,在输入 firstNamelastNameAnswer 后,我'我能够像这样在控制台中打印出值:

{firstName:“Peter”,lastName:“Smith”,答案:{…}}

但是,我想将 answer 的值打印为一个简单的字符串,而不是一个对象。

预期结果:

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

有人知道如何做到这一点吗?

这是我的代码:LIVE DEMO

【问题讨论】:

  • 你总是可以console.log 这个代替:Object.assign({}, this.searchform.value, { answer: this.searchform.value.answer.label })
  • 你可以直接在你的 stackblitz 中复制代码来查看它...stackblitz.com/edit/angular-rvpmjk
  • @DanielWSrimpel 非常感谢兄弟!
  • JSON.stringify(this.searchform.value);试试这个,或者你可以直接在 html 中使用 Json 管道,比如 {{ searchform.value | json}}

标签: angular typescript primeng


【解决方案1】:

p-dropdown 中删除optionLabel="label" 属性,并使用valuelabel 初始化答案对象:

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

现在将以您预期的格式打印。

Here is a fork of the Stackblitz

【讨论】:

  • 非常感谢您的输入兄弟!
【解决方案2】:

这个怎么样?

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

【讨论】:

    【解决方案3】:

    这是因为你有一个数组,你必须访问数组的值

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

    【讨论】:

    • 我不想一张一张打印出来。我想将它们全部打印在一个对象中,就像我在问题中显示的那样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2017-09-16
    • 2016-05-07
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多