TypeScript version: ^3.5.3
For this json
JavaScript
x
7
1
const config = {
2
id: 1,
3
title: "A good day",
4
body: "Very detailed stories"
5
publishedAt: "2021-01-20 12:21:12"
6
}
7
It can be changed to a new title with spread syntax as
JavaScript
1
5
1
const newConfig = {
2
config,
3
title: "A new day"
4
}
5
The final newConfig
data will be
JavaScript
1
7
1
{
2
id: 1,
3
title: "A new day",
4
body: "Very detailed stories"
5
publishedAt: "2021-01-20 12:21:12"
6
}
7
But in this case
JavaScript
1
14
14
1
const config = {
2
id: 1,
3
articleConfig: {
4
version: "2",
5
configs: [
6
{
7
title: "A good day",
8
body: "Very detailed stories"
9
publishedAt: "2021-01-20 12:21:12"
10
}
11
]
12
}
13
}
14
Also want to change title
‘s value. Tried
JavaScript
1
10
10
1
const newConfig = {
2
config,
3
articleConfig: {
4
configs: [
5
{
6
title: "A new day"
7
}
8
]
9
}
10
It will break the pre-defined json schema:
JavaScript
1
12
12
1
const newConfig: {
2
id: number;
3
articleConfig: {
4
version: string;
5
configs: {
6
title: string;
7
body: string;
8
publishedAt: string;
9
}[];
10
};
11
}
12
So is there an easy way to overwrite only one item in this kind of json?
Advertisement
Answer
JavaScript
1
12
12
1
const oldConfig = { /* ... */ };
2
3
const newConfig = {
4
oldConfig,
5
articleConfig: {
6
oldConfig.articleConfig,
7
configs: config.configs.map(config => ({
8
config,
9
title: "A new day"
10
}))
11
};
12