0

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);
panthro
  • 22,779
  • 66
  • 183
  • 324
  • 3
    your syntax seems wrong. Try `users.forEach((item, index, object) => {` – Chris Jan 29 '18 at 20:07
  • You're using `foreach` incorrectly. It's first argument is a function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – jpaugh Jan 29 '18 at 20:08

3 Answers3

9

When passing multiple parameters to an arrow function, enclose them in parentheses:

users.forEach((item, index, object) => { ... }

(See https://developer.mozilla.org/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));
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
1

you need to put all the params into parenthesis like :

users.forEach((item, index, object) => {
andrea06590
  • 1,259
  • 3
  • 10
  • 22
1

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.

mdatsev
  • 3,054
  • 13
  • 28