Version TypeScript :^3.5.3
Pour ce json
const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" }
Il peut être remplacé par un nouveau titre avec une syntaxe étendue comme
const newConfig = { ...config, title: "A new day" }
Le dernier newConfig
les données seront
{ id: 1, title: "A new day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" }
Mais dans ce cas
const config = { id: 1, articleConfig: { version: "2", configs: [ { title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } ] } }
Je veux aussi changer title
sa valeur. Essayé
const newConfig = { ...config, articleConfig: { configs: [ { title: "A new day" } ] }
Cela cassera le schéma json prédéfini :
const newConfig: { id: number; articleConfig: { version: string; configs: { title: string; body: string; publishedAt: string; }[]; }; }
Existe-t-il un moyen simple d'écraser un seul élément dans ce type de JSON ?
Répondre
const oldConfig = { /* ... */ }; const newConfig = { ...oldConfig, articleConfig: { ...oldConfig.articleConfig, configs: config.configs.map(config => ({ ...config, title: "A new day" })) };