JavaScript数组对象到一列csv字符串

时间:2018-08-29 13:53:06

标签: javascript arrays

是否有一种方法可以仅使用每个对象的一个​​属性将数组转换为字符串?

给出:

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

所需

'v21,v22,v23'

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

使用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)