简体   繁体   中英

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 ?

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

A simple map will do it !

 let xs = [{a: 1,b:2}, {a:3,b:4}, {a: 5,b:6}] let out = xs.map(({a,b})=> [a,b]) console.log(out) //=> [ [1,2], [3,4], [5,6] ] 

Here's a pre-ES6 answer to help

 var xs = [{a: 1,b:2}, {a:3,b:4}, {a: 5,b:6}] var out = xs.map(function(x) { return [xa, xb] }) console.log(out) //=> [ [1,2], [3,4], [5,6] ] 

我用这个代码:

x.map(Object.values).join("\\n")

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