【问题标题】:Basic Stringify question with call back function带有回调函数的基本字符串化问题
【发布时间】:2021-11-11 15:52:14
【问题描述】:

所以我刚开始学习json,有一个问题。

const rabbit = {
  name: 'BobJ',
  color: 'black',
  size: null,
  birthDate: new Date(),
  jump: () => {
    console.log(`${name} can jump!`);
  }
}

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return key === 'name' ? 'Elsa' : value;
});
console.log(json)

这个*return key === 'name' ? 'Ellie' : value;* 部分表示如果有'name'键,则将值设置为Ellie,否则返回其原始值。

如果我想在该代码中拥有 2 个以上的键,该怎么办?像 namecolor?代码会是什么样子?

【问题讨论】:

  • 你能提供一个你想要的输出的例子吗?您要制作{name: "Elsa", color: "black" }吗?

标签: javascript json stringify


【解决方案1】:

您可以放置​​多个if else 条件。

if (key === 'name') {
 return 'Elsa'
} else if (key === 'color') {
  return 'Green'
} 
// if nothing else
return value

您也可以使用switch 语句。或nested ternary

我喜欢为此使用哈希图/对象。

const rabbit = {
  name: 'BobJ',
  color: 'black',
  size: null,
  birthDate: new Date(),
  jump: () => {
    console.log(`${name} can jump!`);
  }
}

const keyMap = {
  name: "Elsa",
  color: "Green",
}

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return keyMap[key] || value
});

console.log(json)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多