【问题标题】:Is there an easy way to change one value in a nested json data with TypeScript?有没有一种简单的方法可以使用 TypeScript 更改嵌套 json 数据中的一个值?
【发布时间】:2021-04-24 15:52:42
【问题描述】:

TypeScript 版本:^3.5.3

对于这个json

const config = {
  id: 1,
  title: "A good day",
  body: "Very detailed stories"
  publishedAt: "2021-01-20 12:21:12"
}

可以改成新标题,展开语法为 as

const newConfig = {
  ...config,
  title: "A new day"
}

最终的newConfig 数据将是

{
  id: 1,
  title: "A new day",
  body: "Very detailed stories"
  publishedAt: "2021-01-20 12:21:12"
}

但在这种情况下

const config = {
  id: 1,
  articleConfig: {
    version: "2",
    configs: [
      {
        title: "A good day",
        body: "Very detailed stories"
        publishedAt: "2021-01-20 12:21:12"
      }
    ]
  }
}

还想更改title 的值。试过了

const newConfig = {
  ...config,
  articleConfig: {
    configs: [
      {
        title: "A new day"
      }
    ]
}

它会破坏预定义的 json 架构:

const newConfig: {
    id: number;
    articleConfig: {
        version: string;
        configs: {
            title: string;
            body: string;
            publishedAt: string;
        }[];
    };
}

那么有没有一种简单的方法可以只覆盖这种 json 中的一项?

【问题讨论】:

  • 记住 json 是 javascript。并且在 javascript 中对象是可变的。无需使用不可变样式复制使事情复杂化。
  • TypeScript 的版本是^3.5.3。那么你的意思是如何让一个新的数据库成为当前的数据库呢?
  • 我想知道为什么一切都是常量。您可以克隆对象并对其进行变异。

标签: javascript json typescript operators spread-syntax


【解决方案1】:
const oldConfig = { /* ... */ };

const newConfig = {
  ...oldConfig,
  articleConfig: {
    ...oldConfig.articleConfig,
    configs: config.configs.map(config => ({
       ...config,
       title: "A new day"
    }))
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2012-01-05
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多