javascript - 如何更新数组中的 map 对象?

标签 javascript

我有一组 map 对象,想更新每个对象的两个属性。

  1. 账号
  2. handlerId

更新:

这是 map 对象数组的样子:

Image of console data

data: {
  COMP_011234567      NYWC-LLUVULylrqhqq5QkMTU: {
    accountId: "1234567      "
    accountKey: "COMP_011234567      "
    accountName: "Test123 "
    adjusterClaimType: "WC"
    adjusterKey: "COMP_01WC-LLUVULylrqhqq5QkMTU"
    assignmentRulesKey: "COMP_011234567      NYWC"
    companyAdjusterId: 1111111
    companyId: "COMP_01"
    exception: false
    handlerId: "-LLUVULylrqhqq5QkMTU"
    key: "COMP_011234567      NYWC-LLUVULylrqhqq5QkMTU"
    lineOfBusiness: "WC"
    name: "WC Med Only Direct Without skills - All states"
    selectedState: "NY"
    tpa: "no"
    tpaCompany: ""
    }
}

I need to trim() accountId and handlerId.


// Already tried this apporach: 

  data.forEach(i => {
    i.accountId = i.accountId.trim();
    i.handlerId = i.handlerId.trim();
  })

最佳答案

您可以使用 Array.prototype.reduce()Object.entries() 不可变地完成它。

  1. 使用 Object.entries 遍历您的内部对象。
  2. 使用 reduce 迭代这个键/值对列表:
    1. 对于每个条目,使用展开运算符将对象映射到浅拷贝。
    2. 然后 trim accountIdhandlerId 并将它们分配给正确的属性。
    3. 最后,将新对象分配给累加器中的右键。

const data = {
  'COMP_011234567      NYWC-LLUVULylrqhqq5QkMTU': {
    accountId: "1234567      ",
    accountKey: "COMP_011234567      ",
    accountName: "Test123 ",
    adjusterClaimType: "WC",
    adjusterKey: "COMP_01WC-LLUVULylrqhqq5QkMTU",
    assignmentRulesKey: "COMP_011234567      NYWC",
    companyAdjusterId: 1111111,
    companyId: "COMP_01",
    exception: false,
    handlerId: "-LLUVULylrqhqq5QkMTU",
    key: "COMP_011234567      NYWC-LLUVULylrqhqq5QkMTU",
    lineOfBusiness: "WC",
    name: "WC Med Only Direct Without skills - All states",
    selectedState: "NY",
    tpa: "no",
    tpaCompany: ""
  }
};


const result = Object.entries(data).reduce((acc, [key, x]) => {
  acc[key] = { ...x, accountId: x.accountId.trim(), handlerId: x.handlerId.trim() };
  return acc;
}, {});

console.log(result);

关于javascript - 如何更新数组中的 map 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55458652/

相关文章:

javascript - 如何在javascript中编码UTF-8字符?

javascript - 使用 Javascript forEach 和 indexOf 在 JSON 中搜索多个过滤器

javascript - 无法从客户端应用程序引用插件中定义的静态方法

javascript - 无法将滚动 Javascript Ticker/Marquee 设置为 100% 宽度

javascript - 选择所有具有指定字符串的div

javascript - 在javascript代码中添加一行

JavaScript/NodeJS : Invoking object methods inside the same object: why is "this." mandatory?

javascript - 通过字符串数组过滤对象数组

javascript - scrollr.js 动画仅发生在位置固定的元素上

javascript - 购物 list 应用程序 : using checkboxes to cross off items