Skip to content
Advertisement

Is there an easy way to change one value in a nested json data with TypeScript?

TypeScript version: ^3.5.3

For this json

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

It can be changed to a new title with spread syntax as

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

The final newConfig data will be

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

But in this case

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

Also want to change title‘s value. Tried

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

It will break the pre-defined json schema:

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

So is there an easy way to overwrite only one item in this kind of json?

Advertisement

Answer

const oldConfig = { /* ... */ };

const newConfig = {
  ...oldConfig,
  articleConfig: {
    ...oldConfig.articleConfig,
    configs: config.configs.map(config => ({
       ...config,
       title: "A new day"
    }))
};
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement