javascript - 将对象拆分为两个属性

标签 javascript underscore.js

这个问题在这里已经有了答案:





Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`

(3 个回答)


8 个月前关闭。




我敢肯定,这是一个非常初学者的问题,很抱歉提出问题,但我在这件事上进行了很好的追捕,但没有运气......我正在寻找“打破”或“扩展”以下内容:

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,但肯定遗漏了一些非常明显的东西。任何帮助将不胜感激,谢谢!

最佳答案

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

关于javascript - 将对象拆分为两个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45035514/

相关文章:

javascript - 检测复选框是否被选中,然后获取 div id

javascript - HTML5 canvas 游戏的 Tileset

javascript - GroupBy items 基于两个键使用 Underscore

mongodb - 从 mongo 集合中仅提取 id

javascript - 使用下划线 sortBy 进行对象排序的数组

javascript - AngularJS UI 网格列中的选择下拉列表不适用于外部 editcellTemplate

javascript - 下拉菜单隐藏在 iframe 后面

javascript - 没有 jquery 移动的 slider 工具提示扩展

javascript - 类型错误 : n is undefined in underscore. min.js

javascript - 下划线模板在 IE 8 中失败并显示 "unexpected identifier"