[英]update object value of all objects in javascript array with eslint error
I have a javascript array like this:我有一个这样的javascript数组:
const arr=[{name:"Test", sex:"Male"},{name:"Test2",sex:"Female"},
{name:"Test3",sex:"Male"}
]
I want to change name of all the objects in the arr to "common" like this:我想将 arr 中所有对象的名称更改为“common”,如下所示:
const arr=[
{name:"common",
sex:"Male"},
{name:"common",
sex:"Female"},
{name:"common",
sex:"Male"}]
What I am doing is:我正在做的是:
arr.map((element) => {
element.name= "common";
return element;
});
using forEach
:使用forEach
:
arr.forEach((element) => {
element.name= "common";
return element;
});
This is working but giving a eslint warning stating:这是有效的,但给出了一个 eslint 警告,说明:
no-param-reassign error
Assignment to property of function parameter 'element'.
How can I fix this without adding a skip for this?如何在不为此添加跳过的情况下解决此问题? Maybe by using forEach or something else?Any leads will be highly appreciated.也许通过使用 forEach 或其他东西?任何线索都将受到高度赞赏。
You're not supposed to change the incoming parameters in a function to prevent unintended behaviors.您不应该更改函数中的传入参数以防止意外行为。 https://eslint.org/docs/rules/no-param-reassign https://eslint.org/docs/rules/no-param-reassign
You can change turn off this rule or you can reassign the parameter to another variable:您可以更改关闭此规则,也可以将参数重新分配给另一个变量:
arr = arr.map((element) => {
let e = element;
e.name = 'common';
return e;
});
Do like this:这样做:
let arr = [];
arr = arr.map(element => ({ ...element, name: 'common' }));
const common = arr.map((item) => ({name: item.name = 'common', sex:
item.sex}))
console.log(common)
This is object array mapping.这是对象数组映射。 The syntax requires you use element/item and then I used dot notation.语法要求您使用元素/项目,然后我使用点表示法。 Just replace the first item element with "common" and you're good to go!只需将第一个 item 元素替换为“common”就可以了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.