Mat.Now
Mat.Now

Reputation: 1725

convert simple for loop on arrow function es6

Hey I have one question simple for loop and arrow functions in es6. I have simple for loop I try make the same effect using arrow functions. Please look on code:

for(var i = 0; i < app.productsPag.length; i++){
    if(app.productsPag[i]._id == data.id){
        app.productsPag[i].description = data.description
   }
}

Code above works very good. And ES6:

app.productsPag.forEach(item => item._id == data.id).filter(arr => arr.description == data.description)

But his not working.

Upvotes: 1

Views: 4364

Answers (3)

xyiii
xyiii

Reputation: 112

Since you want to manipulate / change existing data, creating another variable would not make any sense.

Btw === also checks the type and is usually preferred over ==

One line:

app.productsPag.find(obj => obj.id === data.id)['description'] = data.description;

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386726

Just find and update with a default object.

var object = (app.productsPag.find(({ _id }) => _id ===data.id) || {})
        .description = data.description;

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 371029

If you want to use .filter, you should use it before the forEach so that you iterate over the filtered array while assigning to the description property:

app.productsPag.filter(({ _id }) => _id === data.id)
  .forEach(product => product.description = data.description);

As comment says, iterating over the objects twice like this is pretty silly - while this looks to be closest to what your original code was trying to achieve, you'd be better using only a single forEach with a test inside:

app.productsPag.forEach((product) => {
  if (product._id === data.id) product.description = data.description;
});

But it sounds like there might only be one matching product. If this is the case, you should use find instead of filter:

const foundProduct = app.productsPag.find(({ _id }) => _id === data.id);
if (foundProduct) foundProduct.description = data.description;

in ES5 syntax, the destructuring in the function parameters is equivalent to the following:

var foundProduct = app.productsPag.find(function(product) {
  return product._id === data.id;
});
if (foundProduct) foundProduct.description = data.description;

Better to use only a single forEach with a test inside if multiple objects can match

Upvotes: 1

Related Questions