简体   繁体   中英

Right syntax of lambda javascript

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?

Try:

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

Notice the curly braces.

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.)

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(); }); 

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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM