将对象拆分为两个属性

新手上路,请多包涵

我敢肯定,下面是一个非常初学者的问题,很抱歉提出这个问题,但我已经很好地解决了这个问题,但没有运气……我希望“打破”或“扩展”以下内容:

 var words = { hello: 2, there: 3, heres: 1, text: 1 }

进入这个:

 var words = [{
  word: 'hello',
  count: 2
}, {
  word: 'there',
  count: 3
}, {
  word: 'heres',
  count: 1
}, {
  word: 'text',
  count: 1
}]

我一直在使用 Underscore.js,但肯定遗漏了一些非常明显的东西。任何帮助将不胜感激,谢谢!

原文由 Matt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 362
2 个回答

您可以使用 Object.keys()map() 执行此操作。

 var words = { hello: 2, there: 3, heres: 1, text: 1 }
var result = Object.keys(words).map(e => ({word: e, count: words[e]}))
console.log(result)

您也可以先创建数组,然后使用 for...in 循环推送对象。

 var words = { hello: 2, there: 3, heres: 1, text: 1 }, result = [];
for(var i in words) result.push({word: i, count: words[i]})
console.log(result)

原文由 Nenad Vracar 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 Array#map 的可能解决方案。

 const words = { hello: 2, there: 3, heres: 1, text: 1 },
      res = Object.keys(words).map(v => ({ word: v, count: words[v] }));

      console.log(res);

或者 Array#reduce

 const words = { hello: 2, there: 3, heres: 1, text: 1 },
      res = Object.keys(words).reduce((s,a) => (s.push({ word: a, count: words[a] }), s), []);

      console.log(res);

原文由 kind user 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题