Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Array of Objects by Property javascript

I have array of objects:

var x = [{a: 1,b:2}, {a:3,b:4}, {a: 5,b:6}];

I need to join array as follows:

1,2 
3,4
5,6

I do not want to use from lodash or underscore

How can I get Join of array of objects ?

like image 275
mrmr68 Avatar asked Aug 03 '16 05:08

mrmr68


People also ask

How do you use join on array of objects in JavaScript?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do I join a split array?

How it works: First, split the title string by the space into an array by using the split() string method. Second, concatenate all elements in the result array into a string by using the join() method. Third, convert the result string to lower case by using the toLowerCase() method.

How do you map an array of objects?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


1 Answers

const x = [{a: 1,b:2}, {a:3,b:4}, {a: 5,b:6}];    
console.log(x.map(Object.values));

Output:

[
  [1,2],
  [3,4],
  [5,6]
]

Furthermore, if you really want a string (not clear from your question)

x
  .map(o => Object.values(o).join(','))
  .join('\n')
like image 103
mash Avatar answered Sep 18 '22 23:09

mash