Right syntax of lambda javascript

41,745

Solution 1

Try:

 var row = {title: "", attribute:"", width: ""};
 list.forEach( list => {
                 row.title = list.label;
                 row.attribute = list.label;
                 row.width = "300px"    
              });

Notice the curly braces.

Solution 2

You need curly brackets, as the part after the => is a function body:

 var row = {title: "", attribute:"", width: ""};
 list.forEach( list => {
   row.title = list.label;
   row.attribute = list.label;
   row.width = "300px";
 });

(Be advised that if this is the code you are actually running, the values in row will be set to the values of the last entry in list.)

Solution 3

You should wrap non-returning statements in arrow function with curly brackets:

var list = [
  { label: 'one'   },
  { label: 'two'   },
  { label: 'three' }
];

var row = {title: "", attribute:"", width: ""};

list.forEach(list => {
  row.title = list.label;
  row.attribute = list.label;
  row.width = "300px";
  console.log('Row is', row);
  console.log();
});

Solution 4

As it stands row will hold the data in each of your loops of .forEach, so you will only be getting the data of the last element that was processed. You want to make a new object to store the data "for each" of these loops, and then have a populated array.

var Row = (title, attribute, width) => {
  this.title = title;
  this.attribute = attribute;
  this.width = width;
};

var rows = [];
list.forEach( item => { 
  rows.push(new Row(list.label, list.label, "300px"));
});

Alternatively, the map function could do what you want in less code.

var rows = list.map( ( item ) => {
  return new Row(item.label, item.label, "300px");
});
Share:
41,745
Juan Reina Pascual
Author by

Juan Reina Pascual

Updated on January 18, 2020

Comments

  • Juan Reina Pascual
    Juan Reina Pascual over 4 years

    I´m trying to set some values within a object using forEach lambda:

     var row = {title: "", attribute:"", width: ""};
     list.forEach( list =>
                     row.title = list.label |
                     row.attribute = list.label |
                     row.width = "300px"    
                  );
    

    Works fine only with a statement row.title = list.label when I add the rest of parameters does not work fine.

    What is the right syntax?

  • Ron Klein
    Ron Klein almost 5 years
    I'm not sure your code demonstrates your point: note that you have a variable named item and you don't use it (in the first snippet)