0

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'
2
  • 1
    how do you chose which property is the correct one ? Commented Aug 29, 2018 at 13:54
  • oops, had an error in JSON, want to use f2 property Commented Aug 29, 2018 at 13:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

You need to put the values of f1, f2 etc in quotes
wouldn't it be better with reduce ?
That's probably a matter of preference. I think the combination of map and join is reasonably clean.
The only thing to be careful of with this, IE doesn't support lambda's(=>) or let's, so if this is running on the client and you need to support IE, you may need to re-write this with a normal function and var's.
0

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)

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.