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

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


当前回答

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 ]
]

使用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” }
]

如果你正在使用lodash,它可以像这样简单:

var arr = _.values(obj);

或者你可以使用Object.assign():

Const obj = {0: 1,1: 2,2: 3}; const arr =对象。分配([],obj); console.log (arr) // arr是[1,2,3]

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

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