如何修改嵌套深层JavaScript对象:将issueKey追加到指定属性字符串末尾
No need to overcomplicate this—here's a straightforward way to modify your nested object as requested:
Step-by-Step Implementation
First, let's start with your original object:
const a = { elementErrors: { errorMessages: [], errors: { project: "Issues with this Issue Type must be created in the same project as the parent." } }, issueKey: "JP-55", status: 400 };
To append the issueKey to the error message in parentheses, simply access the nested error string and concatenate the formatted issueKey using a template literal:
// Append the issueKey wrapped in parentheses a.elementErrors.errors.project += ` (${a.issueKey})`;
Result
After running that line, your object will look exactly like the desired output:
const a = { elementErrors: { errorMessages: [], errors: { project: "Issues with this Issue Type must be created in the same project as the parent (JP-55)." } }, issueKey: "JP-55", status: 400 };
Optional: Add Safety Checks
If there's a chance the nested properties might be missing (e.g., no project error exists), you can add guard clauses to avoid runtime errors:
// Check if all required properties exist before modifying if (a.elementErrors?.errors?.project && a.issueKey) { a.elementErrors.errors.project += ` (${a.issueKey})`; }
This uses optional chaining (?.) to safely access nested properties, ensuring the code only runs if everything is present.
内容的提问来源于stack exchange,提问作者Jorge Guerreiro

