javascript - Lodash 转换对象和字符串的数组混合

标签 javascript arrays json 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();

关于javascript - Lodash 转换对象和字符串的数组混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31481003/

相关文章:

JavaScript : How to get Coordinates from JSON array within dictionary

php - 在PHP中查找数组是否为空

arrays - slice 内的数组

java - ElasticSearch SearchResponse 对象聚合到 JsonObject?

javascript - JavaScript 中音频文件的计时不准确

Javascript 对象字面量 : what exactly is {a, b, c}?

javascript - 以同样的方式随机化两个数组,javascript

javascript - 如何根据 PHP 中的 json 结果在 Javascript 中制作 IF 语句

javascript - Dygraphs.js 未显示第二个值

javascript - 无法在Reactjs中加载js文件