I have a javascript array like this:
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:
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
:
arr.forEach((element) => {
element.name= "common";
return element;
});
This is working but giving a eslint warning stating:
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.
CodePudding user response:
You're not supposed to change the incoming parameters in a function to prevent unintended behaviors. 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;
});
CodePudding user response:
Do like this:
let arr = [];
arr = arr.map(element => ({ ...element, name: 'common' }));
CodePudding user response:
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!