I'm looking at the answer here but when doing:
let users = [{name: 'john', address: '10 king street'}, ....];
users.forEach(item, index, object => {
I get the error:
item is not defined
I need this so I can:
object.splice(index, 1);
I'm looking at the answer here but when doing:
let users = [{name: 'john', address: '10 king street'}, ....];
users.forEach(item, index, object => {
I get the error:
item is not defined
I need this so I can:
object.splice(index, 1);
Share
Improve this question
asked Jan 29, 2018 at 20:05
panthropanthro
24.1k70 gold badges205 silver badges350 bronze badges
2
-
3
your syntax seems wrong. Try
users.forEach((item, index, object) => {
– Chris Commented Jan 29, 2018 at 20:07 -
You're using
foreach
incorrectly. It's first argument is a function. developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – jpaugh Commented Jan 29, 2018 at 20:08
3 Answers
Reset to default 9When passing multiple parameters to an arrow function, enclose them in parentheses:
users.forEach((item, index, object) => { ... }
(See https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Syntax)
For example, to remove all users named "john," do this:
users.forEach((item, index, object) => {
if(item.name == 'john') {
object.splice(index, 1);
}
});
Snippet:
let users = [
{name: 'john', address: '10 king street'},
{name: 'mary', address: '10 queen street'},
{name: 'john', address: '10 prince street'},
{name: 'hank', address: '10 duke street'}
];
users.forEach((item, index, object) => {
if(item.name == 'john') {
object.splice(index, 1);
}
});
console.log(JSON.stringify(users));
you need to put all the params into parenthesis like :
users.forEach((item, index, object) => {
You forgot to enclose the parameters to the arrow function in parentheses.
users.forEach(item, index, object => { /* ... */ })
Doing this means you pass to the function item
, index
, and an arrow function with a single param object
(parentheses not needed with a single param).
Change to this:
users.forEach((item, index, object) => { /* ... */ })
This will pass an arrow function with 3 params: item
is the current item, index
- the index, object
- the object forEach
was called on - in this case users
.