Rod
Rod

Reputation: 15477

JavaScript array objects to one-column csv string

Is there a way to convert my array into a string using only one of the properties of each object?

Given:

[{f1:'v1', f2:'v21'}, {f1:'v2', f2:'v22'}, {f1:'v3', f2:'v23'}]

Desired

'v21,v22,v23'

Upvotes: 0

Views: 371

Answers (2)

Emeeus
Emeeus

Reputation: 5260

Using reduce()

var arr = [{"f1":"v1","f2":"v21"},{"f1":"v2","f2":"v22"},{"f1":"v3","f2":"v23"}];

var res = arr.reduce((a, e)=>{a.push(e.f2); return a },[]).toString()

console.log(res)

Upvotes: 0

Petr Broz
Petr Broz

Reputation: 9942

let input = [{
  f1: 'v1',
  f2: 'v21'
}, {
  f1: 'v2',
  f2: 'v22'
}, {
  f1: 'v3',
  f2: 'v23'
}];
let output = input.map((item) => item.f2).join(',');
console.log(output);

Upvotes: 2

Related Questions