4

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 ?

2
  • Array of arrays ? Commented Aug 3, 2016 at 5:07
  • How Join Array Of objects Commented Aug 3, 2016 at 5:08

3 Answers 3

7
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')
Sign up to request clarification or add additional context in comments.

9 Comments

nice use of Object.values
@Rayon, interesting, I didn't know it had such lousy support. Thanks for the link.
@mash – Chrome 51.0... That is too latest.. Without Polyfill it should not be used...
Btw, it can even be x.map(Object.values)
|
4

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 [x.a, x.b] })
console.log(out)
//=> [ [1,2], [3,4], [5,6] ]

Comments

0

i use this code :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.