Combining the first fields of several objects

Is there a way in javascript to concatenate named / indexed fields (say, one field of each object) of several objects into a string.

var theArray = [{ field1: "TEXT", field2: "VAL" ... }, { field1: "text", field2: "val" ... } ... ]; 

For the sake of ideomatics (ideomatic programming), I would like to know if there is a way to connect the values โ€‹โ€‹of all field1 in an array WITHOUT a for loop.

Sort of

 theArray.getFieldValues[0].join(', '); 

What options do we have?

  • overload Array - wouldnโ€™t do it,
  • auxiliary function - I do not want cycles.

There are filter and grep functions in jQuery, but they only filter elements, I would like to know if there is something like

 theArray.grepNewObject(function(o){ return o.field1; }).join(', '); 
+4
source share
1 answer

You can use map first to get an array of only field1 and then join it:

 theArray.map(function(x){return x.field1}).join(', '); 

Note that in IE 8 and earlier, you must map the map. Alternatively, since you are using jQuery, you can use jQuery.map for a cross-browser solution:

 $.map(theArray, function(x){return x.field1}).join(', '); 
+3
source

Source: https://habr.com/ru/post/1488278/


All Articles