简体   繁体   English

变异嵌套深度 object

[英]Mutate nested deep object

I have this object我有这个 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
}

and I want to mutate it so that the nested project property includes the issueKey property at the end of the string, something like "Issues with this Issue Type must be created in the same project as the parent (JP-55)."我想改变它,以便嵌套的项目属性在字符串的末尾包含 issueKey 属性,例如"Issues with this Issue Type must be created in the same project as the parent (JP-55)."

I know I should show that I tried and I did but I haven't managed to come with the beginning of a solution.我知道我应该证明我已经尝试过并且已经做到了,但是我还没有设法开始解决方案。

The final object would look like this:最终的 object 看起来像这样:

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
    }

Many thanks非常感谢

You want to compute a new property based on some other values.您想要根据其他一些值计算新属性。 Just try to access and override it.只需尝试访问并覆盖它。

If you always have a dot at the end, you can use a mix of split() and template literals .如果最后总是有一个点,则可以混合使用split()template literals

 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 } a.elementErrors.errors.project = `${a.elementErrors.errors.project.split('.')[0]} (${a.issueKey}).`; console.log(a);

PS: Above code will break if there is no . PS:如果没有 上面的代码将中断.

You can use the += operator to 'add' something to the end of the string.您可以使用+=运算符将某些内容“添加”到字符串的末尾。

a.elementErrors.errors.project += ` (${a.issueKey})`;

 let 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 } a.elementErrors.errors.project += ` (${a.issueKey})`; console.log(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM