Lodash变换数组混合对象和字符串



我有一个数组,其中包含对象和字符串的混合。我需要把这个数组转换成另一个对象数组。

输入数组

[
  {"text": "Address"},
  {"text": "NewTag"},
  {"text": "Tag"},
  "Address",
  "Name",
  "Profile",
  {"text": "Name"},
]

输出数组应该是这样的:

[
  {"Tag": "Address", Count: 2},
  {"Tag": "Name", Count: 2},
  {"Tag": "NewTag", Count: 1},
  {"Tag": "Profile", Count: 1},
  {"Tag": "Tag", Count: 1},
]
下面是我的代码(看起来很傻):
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');

我想知道是否有更好更优雅的方法来执行这个操作?

通过使用map()和countBy():

_(arr)
    .map(function(item) {
        return _.get(item, 'text', item);
    })
    .countBy()
    .map(function(value, key) {
        return { Text: key, Count: value };
    })
    .value();

你可以使用Object.create(null)创建一个哈希表,在那里你可以计算数组中的属性,然后使用Object.keys获得它的属性,并使用map构建你的对象。

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

最新更新