[英]How to perform a check on an object key and replace its value?
I have an object in form of:我有一个 object 形式为:
let serviceData = [{title: "Template 1", note: "One time fee", usd: "200", eur: "185", gbp: "165"},
{title: "Template 2", note: "Monthly", usd: "200", eur: "185", gbp: "165"},
{title: "Template 3", note: "One time fee", usd: "200", eur: "185", gbp: "165"}]
What's the standard way to perform a check on the key note
to see if it's equal to monthly
or not, and if it is to replace the value of usd
by multiplying it by 12 and returning the updated object?对关键
note
执行检查以查看它是否等于monthly
的标准方法是什么,以及是否通过将其乘以 12 并返回更新的 object 来替换usd
的值?
You can loop through and modify the objects in place:您可以循环并修改适当的对象:
for (const obj of serviceData) {
if (obj.note === "Monthly") {
obj.usd *= 12;
}
}
If you don't want to clobber the original array, you can make a copy by map
ping it:如果您不想破坏原始数组,可以通过
map
ping 来复制:
const modifiedData = serviceData.map(obj => {
if (obj.note === "Monthly") {
return {...obj, note: obj.note * 12};
}
return {...obj};
});
This utilizes object spread syntax .这利用了 object 扩展语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.