gpt4 book ai didi

How to convert an Object {} to an Array [] of key-value pairs in JavaScript(如何在JavaScript中将对象{}转换为键-值对的数组[])

转载 作者:bug小助手 更新时间:2023-10-25 22:41:59 26 4
gpt4 key购买 nike



I want to convert an object like this:

我想这样转换一个对象:



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


into an array of key-value pairs like this:

转换为如下所示的键-值对数组:



[[1,5],[2,7],[3,0],[4,0]...].


How can I convert an Object to an Array of key-value pairs in JavaScript?

如何在JavaScript中将对象转换为键-值对数组?


更多回答
优秀答案推荐

You can use Object.keys() and map() to do this

您可以使用Object.key()和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) => [key, obj[key]]);

console.log(result);





The best way is to do:

最好的方法是:




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);




Calling entries, as shown here, will return [key, value] pairs, as the caller requested.

如下所示,调用条目将根据调用者的请求返回[key,value]对。


Alternatively, you could call Object.values(obj), which would return only values.

或者,您可以调用Obt.Values(Obj),它将只返回值。




Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.



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




The Object.entries function returns almost the exact output you're asking for, except the keys are strings instead of numbers.

除了键是字符串而不是数字之外,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));





If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.

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





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));





I use an arrow function and Object.assign for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.

在上面的示例中,我为map回调使用了一个箭头函数和Object.Assign,这样我就可以通过利用以下事实来将其保留在一条指令中:Object.Assign返回被赋值的对象,而单指令箭头函数的返回值就是该指令的结果。



This is equivalent to:

这相当于:



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





As mentioned by @TravisClarke in the comments, the map function could be shortened to:

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



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


However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.

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



Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.

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




  • Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.

  • Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.



You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:

您可以更进一步,通过就地修改条目数组而不是将其映射到新数组来完全消除增长:





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));





To recap some of these answers now on 2018, where ES6 is the standard.

现在回顾一下2018年的一些答案,其中ES6是标准。



Starting with the object:

从对象开始:



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



  • Just blindly getting the values on an array, do not care of the keys:





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]






  • Simple getting the pairs on an array:





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






  • Same as previous, but with numeric keys on each pair:





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






  • Using the object property as key for a new array (could create sparse arrays):





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]





This last method, it could also reorganize the array order depending the value of keys. Sometimes this could be the desired behaviour (sometimes don't). But the advantage now is that the values are indexed on the correct array slot, essential and trivial to do searches on it.

最后一种方法,它还可以根据键的值重新组织数组顺序。有时这可能是你想要的行为(有时不是)。但现在的优点是,值被索引到正确的数组槽上,对它进行搜索既重要又琐碎。




  • Map instead of Array



Finally (not part of the original question, but for completeness), if you need to easy search using the key or the value, but you don't want sparse arrays, no duplicates and no reordering without the need to convert to numeric keys (even can access very complex keys), then array (or object) is not what you need. I will recommend Map instead:

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



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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


In Ecmascript 6,

在ECMAScript6中,


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);





Yet another solution if Object.entries won't work for you.

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





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





Use Object.keys and Array#map methods.

使用Object.key和数组#贴图方法。





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);





Use Object.entries to get each element of Object in key & value format, then map through them like this:

使用对象条目以键和值格式获取对象的每个元素,然后按如下方式映射它们:





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);





But, if you are certain that the keys will be in progressive order you can use Object.values and Array#map to do something like this:

但是,如果您确定关键点将按递增顺序排列,则可以使用Object.Values和数组#贴图来执行以下操作:





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);





You can use Object.values([]), you might need this polyfill if you don't already:

您可以使用Object.Values([]),如果您尚未需要此多边形填充,则可能需要:



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


https://stackoverflow.com/a/54822153/846348

Https://stackoverflow.com/a/54822153/846348



Then you can just do:

然后,您只需执行以下操作:



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


Just remember that arrays in js can only use numerical keys so if you used something else in the object then those will become `0,1,2...x``

请记住,js中的数组只能使用数字键,因此如果您在对象中使用了其他键,则这些数组将变为`0,1,2...x``



It can be useful to remove duplicates for example if you have a unique key.

例如,如果您有唯一的密钥,则删除重复项可能很有用。



var obj = {};
object[uniqueKey] = '...';


With lodash, in addition to the answer provided above, you can also have the key in the output array.

使用lowash,除了上面提供的答案之外,您还可以在输出数组中拥有键。



Without the object keys in the output array



for:

用于:



const array = _.values(obj);


If obj is the following:

如果obj为以下值:



{ “art”: { id: 1,  title: “aaaa” }, “fiction”: { id: 22,  title: “7777”} }


Then array will be:

则array将为:



[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]


With the object keys in the output array



If you write instead ('genre' is a string that you choose):

如果你改为写('genre'是你选择的字符串):



const array= _.map(obj, (val, id) => {
return { ...val, genre: key };
});


You will get:

您将获得:



[ 
{ id: 1, title: “aaaa” , genre: “art”},
{ id: 22, title: “7777”, genre: “fiction” }
]


If you are using lodash, it could be as simple as this:

如果你正在使用lodash,它可能是这样简单的:



var arr = _.values(obj);


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]]
});


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



This is my solution, i have the same issue and its seems like this solution work for me.




yourObj = [].concat(yourObj);


or you can use Object.assign():

或者,您可以使用Object.Assign():




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





you can use 3 methods convert object into array (reference for anyone not only for this question (3rd on is the most suitable,answer for this question)
Object.keys() ,Object.values(),andObject.entries()

您可以使用3种方法将对象转换为数组(任何人都可以参考,不仅对于这个问题(第三个是最合适的,这个问题的答案)、对象键()、对象值()和对象项()


examples for 3 methods


use Object.keys()


const text= {
quote: 'hello world',
author: 'unknown'
};

const propertyNames = Object.keys(text);

console.log(propertyNames);

result
[ 'quote', 'author' ]


use Object.values()


const propertyValues = Object.values(text);

console.log(propertyValues);


result

结果


[ 'Hello world', 'unknown' ]


use Object.entires()


const propertyValues = Object.entires(text);

console.log(propertyValues);


result

结果


[ [ 'quote', 'Hello world' ], [ 'author', 'unknown' ] ]


Here is a "new" way with es6 using the spread operator in conjunction with Object.entries.

这里是ES6的一种“新”方式,它结合使用了扩散运算符和对象条目。


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


Use for in

用于在



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));


Recursive convert object to array

递归地将对象转换为数组



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


We can change Number to String type for Key like below:

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





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);





you can use _.castArray(obj).

您可以使用_.CastArray(Obj)。



example:

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

示例:_.CastArray({‘a’:1});//=>[{‘a’:1}]





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

result = Object.entries(obj).map((key,value) => [parseInt(key,10), value])

console.log(result);







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 arr = [...new Map(Object.entries(obj))];
console.log(arr);




You can convert your Object to Map first and then use the spread operator to convert the Map into an array , arr is now an array of key-value pairs represented as arrays within the map.

您可以首先将对象转换为贴图,然后使用扩散操作符将贴图转换为数组,Arr现在是表示为贴图中数组的键-值对的数组。


更多回答

@blvckasvp Are you using numbers as your keys? If not, when it tries to convert your key to a number it will fail and return NaN instead. If you want to use strings as your keys, change the return from [Number(key), obj[key]] to [key, obj[key]] or use the Object.entries as @Pila suggested in their answer

@blvckasvp你用数字做钥匙了吗?否则,当它尝试将您的密钥转换为数字时,它将失败并返回NaN。如果要使用字符串作为密钥,请将[number(Key),obj[key]]的返回值更改为[key,obj[key]],或者按照@Pila在答案中的建议使用对象条目

for me, it's worked fine. I need to convert the below object let res ={"5":"ManuscriptRequestId","4":"PublishRequestId","9":"AuthorIdentificationId","1":"VisitRequestId","6":"InformationRequestId","3":"RareDocumnetsRequestId","2":"RarePhotoRequestId","7":"BookPurchaseRequestId","8":"StatmentRequestId"} const dataArray = Object.entries(res).map(([key, value]) => ({ key, value }));

对我来说,它运行得很好。我需要转换下面的对象let res={“5”:“ManuscriptRequestId”,“4”:“PublishRequestId”,“9”:“AuthorIdentificationId”,“1”:“VisitRequestId”,“6”:“InformationRequestId”,“3”:“RareDocumnetsRequestId”,“2”:“RarePhotoRequestId”,“7”:“BookPurcheeRequestId”,“8”:“StatmentRequestId”}const dataArray=Object.Entries(Res).map(([key,Value])=>({key,value}));

FYI : Object.entries will return [key,value], but the key will be a string, value will differ.

仅供参考:对象条目将返回[Key,Value],但Key将是字符串,值将不同。

Using Object.fromEntries() will convert the [key, value] pairs back to an object.

使用Object.from mEntry()会将[key,value]对转换回一个对象。

Object.values() won't have the correct 'keys'...assuming the object's keys are all numbers.

假如对象的键都是数字,那么对象的值()将不会有正确的“键”。

I like the functional approach. As a shorter alternative: Object.entries(obj).map(e => [+e[0], e[1]]);

我喜欢这种功能性的方法。作为较短的备选方案:对象条目(Obj).map(e=>[+e[0],e[1]]);

The fourth bullet point and onward is completely irrelevant to the question, and the rest of your answer is just summarizing the top three answers here. This answer does not bring anything to the discussion that was not already here or is not completely irrelevant.

第四个要点及后续部分与问题完全无关,您的答案的其余部分只是总结了这里的前三个答案。这一回答没有给讨论带来任何已经不在这里或并非完全无关的东西。

Yes, as the first line state, this is a summary of answers, then update them to use modern ES6 techniques instead of full blow functions. The fourth answer is useful when you are moving JSON arrays from a language that supports associative arrays (e.g. PHP).

是的,作为第一行状态,这是答案的摘要,然后更新它们以使用现代ES6技术而不是全速功能。当您从支持关联数组的语言(例如PHP)迁移JSON数组时,第四个答案很有用。

All of the methods provided here have already been provided in their plain form in two of the top three answers, they are not in functions so I dont know what you're on about there. As far as the 4th, as I said it is completely irrelevant to the question asked. It might be relevant to a different question, but not this one. Regardless, JSON is JSON whether it is created using PHP, JavaScript, or Haskell.

这里提供的所有方法都已经在前三个答案中的两个中以简单的形式提供了,它们不在函数中,所以我不知道您在那里想说什么。至于4号,正如我所说的,它与所提出的问题完全无关。它可能与另一个问题有关,但不是这个问题。无论如何,JSON都是JSON,无论它是使用PHP、JavaScript还是Haskell创建的。

This worked for me. I experienced an issue where importing JSON added indexes that made it impossible to use Angulars ngFor loop. This removed the indexes while preserving the structure.

这对我很管用。我遇到了一个问题,导入JSON会添加索引,从而无法使用Angulars ngFor循环。这在保留结构的同时删除了索引。

@RAC +1 for using "indexes" instead of "indices". Begone, archaic (ie. arbitrary and meaninglessly deviant) English traditions!

@RAC+1,表示使用“INDEX”而不是“INDEX”。滚开,古语(即。武断和毫无意义的离经叛道)英国传统!

While this is informative, the question is more specific and can be answered just by the third part. Please consider editing your answer to just answer the question.

虽然这是信息性的,但问题更具体,只能通过第三部分来回答。请考虑编辑您的答案以仅回答问题。

yeah, I did mentioned above before answering question anyway I bold it out ( I put 3 answers for reference for those who need to learn about this methods maybe you are pro but I mentioned it for beginners)

是的,我在回答问题之前已经提到过了,但我还是大胆地提出来了(我给那些需要学习这个方法的人提供了3个答案供参考也许你是专业的,但我提到它是给初学者的)

Using the spread operator here is redundant. There is no need to use it because Object.entries() already returns a 2d array in the expected format.

在这里使用扩散运算符是多余的。不需要使用它,因为对象条目()已经以预期的格式返回了一个二维数组。

Yep, you are right. The outer array isn't needed either, so I've updated the code to get rid of that as well!

是的,你说得对。外部数组也不是必需的,所以我也更新了代码来去掉它!

This produces the wrong answer. Try running the snippet.

这就产生了错误的答案。尝试运行该代码片段。

You get the exact same result with const arr = Object.entries(obj);. The Map conversion is unnecessary. This has been mentioned several times, and it does not match the expected result.

使用const arr=Obt.Entries(Obj);可以得到完全相同的结果。贴图转换是不必要的。这已经被提到过几次了,与预期的结果不符。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com