Array transform array of Lodash objects and strings
I have an array containing a mix of objects and strings. I need to convert an array to another array of objects.
Input array:
[
{"text": "Address"},
{"text": "NewTag"},
{"text": "Tag"},
"Address",
"Name",
"Profile",
{"text": "Name"},
]
The out element should look like this:
[
{"Tag": "Address", Count: 2},
{"Tag": "Name", Count: 2},
{"Tag": "NewTag", Count: 1},
{"Tag": "Profile", Count: 1},
{"Tag": "Tag", Count: 1},
]
Here is my code (looks silly):
var tags = [], tansformedTags=[];
for (var i = 0; i < input.length; i++) {
if (_.isObject(input[i])) {
tags.push(input[i]['text']);
} else {
tags.push(input[i]);
}
}
tags = _.countBy(tags, _.identity);
for (var property in tags) {
if (!tags.hasOwnProperty(property)) {
continue;
}
tansformedTags.push({ "Tag": property, "Count": tags[property] });
}
return _.sortByOrder(tansformedTags, 'Tag');
I want to know if there is a better and elegant way to accomplish this operation?
+3
source to share
2 answers
Using map () and countBy ()
_(arr)
.map(function(item) {
return _.get(item, 'text', item);
})
.countBy()
.map(function(value, key) {
return { Text: key, Count: value };
})
.value();
+2
source to share
You can use Object.create(null)
to create a hash table where you can count the properties in your array and then get its properties with Object.keys
and use map
to create your objects.
var count = Object.create(null);
myArray.forEach(function(item) {
var prop = Object(item) === item ? item.text : item;
count[prop] = (count[prop] || 0) + 1;
});
Object.keys(count).sort().map(function(key) {
return {Tag: key, Count: count[key]};
});
+2
source to share