现在有一个对象名为 map 有属性 a, b, c
表示为:
Object {a: 1, b: 2, c: 3}
现在想把这个对象变为对象数组,形式如下:
[{name : 'a', value : 1}, {name : 'b', value : 2}, {name : 'c', value : 3}]
请问应该怎么做呢?
另外能不能麻烦各位推荐一下 JavaScript 的优秀的入门 /参考书籍?谢谢了
1
whahuzhihao 2016-02-22 09:59:09 +08:00 1
手动遍历可以么
``` var o = {a:1,b:2,c:3}; var no = []; for(var k in o) { no.push({name:k,value:o[k]}); } console.log(no); ``` |
2
oct16 2016-02-22 10:03:17 +08:00 1
var arr = [];
var obj = {a:1,b:2,c:3}; var temp; for(var key in obj){ temp = {}; temp.name = key; temp.value = obj[key]; arr.push(temp); } console.log(arr) |
3
hienchu 2016-02-22 10:04:52 +08:00 1
如果有其他语言基础,我还是推荐这本[JavaScript: The Good Parts]( http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?s=books&ie=UTF8&qid=1456106764&sr=1-1&keywords=the+good+parts)
|
4
jarlyyn 2016-02-22 10:11:18 +08:00 1
楼主有没有听说过 Lodash/underscore ?
|
5
jarlyyn 2016-02-22 10:22:20 +08:00 1
|
6
FrankFang128 2016-02-22 10:26:55 +08:00 1
无法保证顺序
|
7
otakustay 2016-02-22 11:45:56 +08:00 1
Object.entries(o).map(([name, value]) => ({name, value}));
|
8
ChefIsAwesome 2016-02-22 12:03:56 +08:00 1
遍历一下不就行了,不知道楼主纠结在哪
|
9
ncwhale 2016-02-22 13:12:46 +08:00 1
{name:k, value: v} for k,v of map
|
10
hanai 2016-02-22 13:18:06 +08:00 1
Object.keys(obj).map(key => {name: key, value: obj[key]})
|
11
exoticknight 2016-02-22 13:19:35 +08:00 1
7 楼 es2015 正解
|
12
mmzer 2016-02-22 14:12:50 +08:00 1
var arr=[],i = 0;
var obj = {a:1,b:2,c:3} for(var k in obj){ if(obj[k]){ arr[i++] = function(){ return { name:k, value:obj[k] } } (); } } console.log(arr); |
13
otakustay 2016-02-22 14:49:39 +08:00 1
@exoticknight 还真不是 2015 的, entries 是 2016 的
|
14
sinalvee 2016-02-22 15:47:47 +08:00 1
|
15
yangxiongguo 2016-02-22 15:52:51 +08:00 1
7 楼跟 10 楼都是手撸的吗,都报错了。
|
16
klesh 2016-02-22 18:32:22 +08:00
lodash:
var pairs = _.map(o, function(v, k) { return { name: k, value: v }; }); |
17
exoticknight 2016-02-22 19:14:44 +08:00
@otakustay 果然是,是我技术太渣了= =
|
18
exoticknight 2016-02-22 19:15:03 +08:00
@yangxiongguo 基本没有浏览器支持 es6/7 ……
|
19
dustinth 2016-02-22 20:38:17 +08:00
underscore 或者 lodash 应该成为标配...自从用了就离不开了.
|
20
magicdawn 2016-02-23 09:45:39 +08:00
lodash
```js var obj = {a: 1, b: 2, c: 3}; _.map(obj, (v,k) => { return { name: k, value: v }; }); ``` |