这个问题在这里已经有了答案:
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/