将对象拆分为两个属性
Split object into two properties
我确定下面是一个非常初学者的问题,很抱歉提出这个问题,但我已经很好地解决了这个问题,但运气不佳......我正在寻找 'break' 或 'expand' 以下:
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)
可能的解决方案使用 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);
下面是一个使用下划线的 map 函数的解决方案:
words = _.map(words, (v, k) => ({word: k, count: v}));
Underscore 的映射可以遍历一个对象。迭代器的第一个参数是值,第二个参数是键。
let object = {
"06.10 15:00": 3.035,
"06.10 21:00": 3.001,
};
let arr = [];
for (const [key, value] of Object.entries(object)) {
arr.push({ date: key, value: value });
}
console.log(arr);
我确定下面是一个非常初学者的问题,很抱歉提出这个问题,但我已经很好地解决了这个问题,但运气不佳......我正在寻找 'break' 或 'expand' 以下:
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)
可能的解决方案使用 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);
下面是一个使用下划线的 map 函数的解决方案:
words = _.map(words, (v, k) => ({word: k, count: v}));
Underscore 的映射可以遍历一个对象。迭代器的第一个参数是值,第二个参数是键。
let object = {
"06.10 15:00": 3.035,
"06.10 21:00": 3.001,
};
let arr = [];
for (const [key, value] of Object.entries(object)) {
arr.push({ date: key, value: value });
}
console.log(arr);