我想像这样转换一个对象:
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
输入一个键值对数组,如下所示:
[[1,5],[2,7],[3,0],[4,0]...].
如何将对象转换为JavaScript中的键值对数组?
我想像这样转换一个对象:
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
输入一个键值对数组,如下所示:
[[1,5],[2,7],[3,0],[4,0]...].
如何将对象转换为JavaScript中的键值对数组?
当前回答
在Ecmascript 6中,
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
var res = Object.entries(obj);
console.log(res);
var obj = “1”:5 “2”:7, “3”:0, “4”:0, “5”:0, “6”:0, “7”:0, “8”:0, “9”:0, “10”:0, “11”:0, “12”:0 ); var res = Object.entries(obj); 游戏机。log (res);
其他回答
使用lodash,除了上面提供的答案外,还可以将键放在输出数组中。
输出数组中没有对象键
for:
const array = _.values(obj);
如果obj为以下内容:
{ “art”: { id: 1, title: “aaaa” }, “fiction”: { id: 22, title: “7777”} }
那么数组将是:
[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]
使用输出数组中的对象键
如果你写('genre'是你选择的字符串):
const array= _.map(obj, (val, id) => {
return { ...val, genre: key };
});
你会得到:
[
{ id: 1, title: “aaaa” , genre: “art”},
{ id: 22, title: “7777”, genre: “fiction” }
]
你可以使用Object.keys()和map()来做到这一点
var obj = {“1”:5,“2”:7,“3”:0,“4”:0,“5”:0,“6”:0,“7”:0,“8”:0,“9”:0,“10”:0,“11”:0,“12”:0} var result = Object.keys(obj).map((key) => [Number(key), obj[key]]); 控制台.log(结果);
在Ecmascript 6中,
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
var res = Object.entries(obj);
console.log(res);
var obj = “1”:5 “2”:7, “3”:0, “4”:0, “5”:0, “6”:0, “7”:0, “8”:0, “9”:0, “10”:0, “11”:0, “12”:0 ); var res = Object.entries(obj); 游戏机。log (res);
我们可以将数字改为字符串类型的键如下所示:
var obj = {“1”:5,“2”:7,“3”:0,“4”:0,“5”:0,“6”:0,“7”:0,“8”:0,“9”:0,“10”:0,“11”:0,“12”:0} var result = Object.keys(obj).map(function(key) { 返回 [字符串(键), 对象[键]]; }); 控制台.log(结果);
你可以使用3个方法将对象转换为数组(任何人都可以参考,不仅是这个问题(第三个是最合适的,回答这个问题) 种(),Object.values (), andObject.entries ()
3种方法的示例
使用种()
const text= {
quote: 'hello world',
author: 'unknown'
};
const propertyNames = Object.keys(text);
console.log(propertyNames);
result
[ 'quote', 'author' ]
使用Object.values ()
const propertyValues = Object.values(text);
console.log(propertyValues);
结果
[ 'Hello world', 'unknown' ]
使用Object.entires ()
const propertyValues = Object.entires(text);
console.log(propertyValues);
结果
[ [ 'quote', 'Hello world' ], [ 'author', 'unknown' ] ]