如何在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中的键值对数组?

1268168 次浏览

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


console.log(result);

使用Object.keysArray#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
};
// get all object property names
var res = Object.keys(obj)
// iterate over them and generate the array
.map(function(k) {
// generate the array element
return [+k, obj[k]];
});


console.log(res);

在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);
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 result = Object.entries(obj);


console.log(result);

如这里所示,调用entries将返回调用者所请求的[key, value]对。

或者,你可以调用Object.values(obj),它只返回值。

Object.entries()返回一个数组,其元素是与可枚举属性[key, value]对相对应的数组,该属性直接在object上找到。属性的顺序与手动遍历对象的属性值所给出的顺序相同。

- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Description

Object.entries函数返回几乎完全相同的输出,除了键是字符串而不是数字。

const 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};


console.log(Object.entries(obj));

如果需要键为数字,则可以使用回调函数将结果映射到一个新数组,该回调函数将每对中的键替换为由它强制生成的数字。

const 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};


const toNumericPairs = input => {
const entries = Object.entries(input);
return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));
}


console.log(toNumericPairs(obj));

在上面的例子中,我使用了一个箭头函数和Object.assign作为map回调函数,这样我就可以利用Object.assign返回被赋值的对象,而单个指令箭头函数的返回值是该指令的结果,从而将它保留在一条指令中。

这相当于:

entry => {
entry[0] = +entry[0];
return entry;
}

正如@TravisClarke在评论中提到的,地图功能可以缩短为:

entry => [ +entry[0], entry[1] ]

但是,这将为每个键-值对创建一个新数组,而不是就地修改现有数组,从而使创建的键-值对数组的数量增加一倍。虽然原始条目数组仍然是可访问的,但它及其条目将不会被垃圾收集。

现在,尽管使用我们的in-place方法仍然使用两个数组来保存键-值对(输入数组和输出数组),但数组的总数只改变了一个。输入和输出数组实际上并不是由数组填充的,而是对数组的引用,而这些引用在内存中所占的空间可以忽略不计。

  • 就地修改每个键-值对只会增加很少的内存,但是需要多输入几个字符。
  • 为每个键-值对创建一个新数组会使所需的内存增加一倍,但需要输入的字符会减少一些。

你可以更进一步,通过就地修改entries数组而不是将其映射到一个新的数组来消除增长:

const 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};


const toNumericPairs = input => {
const entries = Object.entries(obj);
entries.forEach(entry => entry[0] = +entry[0]);
return entries;
}


console.log(toNumericPairs(obj));

如果Object.entries不适合你,还有另一个解决方案。

const obj = {
'1': 29,
'2': 42
};
const arr = Array.from(Object.keys(obj), k=>[`${k}`, obj[k]]);
console.log(arr);

使用因为在

var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
"8":0, "9":0, "10":0, "11":0, "12":0 };


var objectToArray = function(obj) {
var _arr = [];


for (var key in obj) {
_arr.push([key, obj[key]]);
}
return _arr;
}


console.log(objectToArray(obj));

递归转换对象到数组

function is_object(mixed_var) {
if (mixed_var instanceof Array) {
return false;
} else {
return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
}
}




function objectToArray(obj) {
var array = [], tempObject;
for (var key in obj) {


tempObject = obj[key];


if (is_object(obj[key])) {
tempObject = objectToArray(obj[key]);
}
array[key] = tempObject;
}
return array;
}

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

var arr = _.values(obj);

使用lodash,除了上面提供的答案外,还可以将键放在输出数组中。

输出数组中没有对象键

:

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.entrieskey & value格式获取Object的每个元素,然后像这样通过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 res = Object.entries(obj).map(([k, v]) => ([Number(k), v]));


console.log(res);

但是,如果你确定键将在进步的顺序中,你可以使用Object.valuesArray#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};


// idx is the index, you can use any logic to increment it (starts from 0)
let result = Object.values(obj).map((e, idx) => ([++idx, e]));


console.log(result);

你可以使用_.castArray (obj)

< p >的例子: _。castArray({'a': 1}); / / =比;[{'a': 1}] < /代码> < / p >

在ES6成为标准的2018年,我们来回顾一下这些答案。

从对象开始:

let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
  • 只是盲目地获取数组的值,不关心键:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.values(obj));
//[9,8,7,6,5,4,3,2,1,0,5]

  • 简单地获取数组上的对:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj));
//[["1",9],["2",8],["3",7],["4",6],["5",5],["6",4],["7",3],["8",2],["9",1],["10",0],["12",5]]

  • 和前面一样,但每对上都有数字键:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).map(([k,v])=>[+k,v]));
//[[1,9],[2,8],[3,7],[4,6],[5,5],[6,4],[7,3],[8,2],[9,1],[10,0],[12,5]]

  • 使用object属性作为新数组的键(可以创建稀疏数组):

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).reduce((ini,[k,v])=>(ini[k]=v,ini),[]));
//[undefined,9,8,7,6,5,4,3,2,1,0,undefined,5]

最后一个方法,它还可以根据键的值重新组织数组的顺序。有时这可能是期望的行为(有时不是)。但是现在的优点是值在正确的数组槽上建立索引,这对于在它上进行搜索至关重要。

  • 用Map代替Array

最后(不是最初问题的一部分,但为了完整性),如果你需要使用键或值轻松搜索,但你不想要稀疏数组,没有重复,没有重新排序,而不需要转换为数字键(甚至可以访问非常复杂的键),那么数组(或对象)不是你需要的。我将推荐Map代替:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

let r=new Map(Object.entries(obj));
r.get("4"); //6
r.has(8); //true

我们可以将数字改为字符串类型的键如下所示:

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) {
return [String(key), obj[key]];
});
    

console.log(result);

这是我的解决方案,我有同样的问题,似乎这个解决方案为我工作。

yourObj = [].concat(yourObj);

你可以使用Object.values([]),如果你不需要,你可能需要这个填充:

const objectToValuesPolyfill = (object) => {
return Object.keys(object).map(key => object[key]);
};
Object.values = Object.values || objectToValuesPolyfill;

https://stackoverflow.com/a/54822153/846348 < a href = " https://stackoverflow.com/a/54822153/846348 " > < / >

然后你可以这样做:

var object = {1: 'hello', 2: 'world'};
var array = Object.values(object);

记住,js中的数组只能使用数字键所以如果你在对象中使用了其他键那么这些键就会变成' 0,1,2…x ' '

例如,如果您有一个唯一的密钥,那么删除重复的密钥就很有用。

var obj = {};
object[uniqueKey] = '...';
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 }
let objectKeys = Object.keys(obj);


let answer = objectKeys.map(value => {
return [value + ':' + obj[value]]
});

这是一个“新”;方法与es6使用spread操作符结合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 ]
]
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

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

const obj = { 0: 1, 1: 2, 2: 3};
const arr = Object.assign([], obj);
console.log(arr)
// arr is [1, 2, 3]

你可以使用3个方法将对象转换为数组(任何人的参考不仅是这个问题(第三个是最合适的,回答这个问题) Object.keys()Object.values() andObject.entries() < / p >

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