繁体   English   中英

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

[英]Lodash transform array mix of objects and strings

我有一个包含对象和字符串混合的数组。 我需要将数组转换为另一个对象数组。

输入数组:

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

out数组应该是这样的:

[
  {"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');

我想知道是否有更好,更优雅的方式来执行此操作?

您可以使用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]};
});

通过使用map()countBy()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM