我有一组 map 对象,想更新每个对象的两个属性。
- 账号
- handlerId
更新:
这是 map 对象数组的样子:
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() 不可变地完成它。
- 使用
Object.entries
遍历您的内部对象。 - 使用
reduce
迭代这个键/值对列表:- 对于每个条目,使用展开运算符将对象映射到浅拷贝。
- 然后 trim
accountId
和handlerId
并将它们分配给正确的属性。 - 最后,将新对象分配给累加器中的右键。
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/