我想像这样转换一个对象:

{"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中的键值对数组?


当前回答

另一个解决方案是Object。输入不适合你。

const obj = { '1': 29, '2': 42 }; const arr = Array.from(Object.keys(obj), k=>['${k}', obj[k]]); 控制台.log(到达);

其他回答

你可以使用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(结果);

你可以使用_.castArray(obj)。

例子: _。castArray({'a': 1}); // => [{'a': 1}]

const persons = { 
    john: { age: 23, year:2010},
    jack: { age: 22, year:2011},
    jenny: { age: 21, year:2012}
}
const resultArray = Object.keys(persons).map(index => {
    let person = persons[index];
    return person;
});

//use this for not indexed object to change array

下面是es6使用扩展操作符和Object.entries的“新”方法。

const data = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

const dataSpread = [...Object.entries(data)];

// data spread value is now:
[
  [ '1', 5 ],  [ '2', 7 ],
  [ '3', 0 ],  [ '4', 0 ],
  [ '5', 0 ],  [ '6', 0 ],
  [ '7', 0 ],  [ '8', 0 ],
  [ '9', 0 ],  [ '10', 0 ],
  [ '11', 0 ], [ '12', 0 ]
]

你可以使用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' ] ]