I need to get array of objects from array of strings. For examaple:
var arr = ["1005", "1005", "1005", "1006", "1006", "1006", "1007", "1007"];
var result = arr.reduce((iss, index) => {
iss[index] = (iss[index] || 0) + 1;
return iss
}, {});
and the result would be
{1005: 3, 1006: 3, 1007: 2}
So is there a way to get next output:
[{"1005":3},{"1006":3},{"1007":2}]
asked Feb 1, 2018 at 12:52
WannaBeBetter
811 gold badge2 silver badges13 bronze badges
-
1Why? There is no advantage of that structure.Jonas Wilms– Jonas Wilms2018年02月01日 12:54:15 +00:00Commented Feb 1, 2018 at 12:54
2 Answers 2
If you really want that:
result = Object.entries(result).map(([key, value]) => ({[key]: value}));
answered Feb 1, 2018 at 12:55
Jonas Wilms
139k20 gold badges164 silver badges164 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
WannaBeBetter
Thank you very much! All of you help me a lot!
You can extend result by iterating its keys
result = Object.keys ( result ).map( s => ({ [s] : result[s] }) );
answered Feb 1, 2018 at 12:55
gurvinder372
68.6k11 gold badges78 silver badges98 bronze badges
Comments
lang-js