【问题标题】:Return as new JSON object作为新的 JSON 对象返回
【发布时间】:2020-09-22 01:37:38
【问题描述】:

我有一个这样的返回对象:

table A: true
table B: true
table C: ""
value A: "AB"
value B: "CD"
value C: ""

在一个表单中,表 A - C 是复选框,输入的值属于复选框。有没有办法像这样将具有真实条件和值的复选框作为新的 JSON 对象一起返回?

 "newRecord": "[{\"table\": \"table A *,table B *\",\"parameters\": \"AB, CD\"}

根据我的理解,我需要循环检查复选框,并且对于每个真实条件,找到值并将它们作为新对象推送到 newRecord 中,并以值作为参数。

新手,尝试编写这段代码,不知道如何使其工作

 let result = JSON.parse(JSON.stringify(this.newForm.value));
  this.newForm.value.checkboxSelection.forEach((element) => {
        if(element.checkboxSelection === true) {
          result.newRecord[index].push();
        }
 });

【问题讨论】:

  • 在你完成构建结果之前不要打电话给JSON.stringify。永远不要手动修改 JSON 字符串。
  • 你的话有道理,但代码有点混乱。你能提供一些表格的示例html吗?还是返回对象的字符串化版本?

标签: javascript json angular typescript


【解决方案1】:

你的意思是这样吗?

const data = {
  'table A': true,
  'table B': true,
  'table C': "",
  'value A': "AB",
  'value B': "CD",
  'value C': "",
};

const result = Object.keys(data).reduce((acc, key) => {
  if (!data[key]) return acc;

  const group: string = key.split(' ')[0];

  if (acc[group]) acc[group] += (', ' + key);
  else acc[group] = key;

  return acc;
}, {});

console.log(result);

打印

{table: "table A, table B", value: "value A, value B"}

https://stackblitz.com/edit/typescript-jgyqyu?file=index.ts

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2023-04-08
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多