有没有一种简单的方法可以使用 TypeScript 更改嵌套 json 数据中的一个值?
Is there an easy way to change one value in a nested json data with TypeScript?
TypeScript 版本:^3.5.3
为此json
const config = {
id: 1,
title: "A good day",
body: "Very detailed stories"
publishedAt: "2021-01-20 12:21:12"
}
它可以更改为新的标题,扩展语法为
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"
}
]
}
它将破坏 pre-defined json 模式:
const newConfig: {
id: number;
articleConfig: {
version: string;
configs: {
title: string;
body: string;
publishedAt: string;
}[];
};
}
那么有没有一种简单的方法可以只覆盖这种json中的一项?
const oldConfig = { /* ... */ };
const newConfig = {
...oldConfig,
articleConfig: {
...oldConfig.articleConfig,
configs: config.configs.map(config => ({
...config,
title: "A new day"
}))
};
TypeScript 版本:^3.5.3
为此json
const config = {
id: 1,
title: "A good day",
body: "Very detailed stories"
publishedAt: "2021-01-20 12:21:12"
}
它可以更改为新的标题,扩展语法为
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"
}
]
}
它将破坏 pre-defined json 模式:
const newConfig: {
id: number;
articleConfig: {
version: string;
configs: {
title: string;
body: string;
publishedAt: string;
}[];
};
}
那么有没有一种简单的方法可以只覆盖这种json中的一项?
const oldConfig = { /* ... */ };
const newConfig = {
...oldConfig,
articleConfig: {
...oldConfig.articleConfig,
configs: config.configs.map(config => ({
...config,
title: "A new day"
}))
};