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'
Maor Refaeli
2,5372 gold badges21 silver badges34 bronze badges
asked Aug 29, 2018 at 13:53
Rod
15.6k36 gold badges137 silver badges275 bronze badges
-
1how do you chose which property is the correct one ?jonatjano– jonatjano2018年08月29日 13:54:52 +00:00Commented Aug 29, 2018 at 13:54
-
oops, had an error in JSON, want to use f2 propertyRod– Rod2018年08月29日 13:56:09 +00:00Commented Aug 29, 2018 at 13:56
2 Answers 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
Jackson
You need to put the values of
f1, f2 etc in quotesjonatjano
wouldn't it be better with
reduce ?Petr Broz
That's probably a matter of preference. I think the combination of
map and join is reasonably clean.Tyler
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.lang-js