Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

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?

like image 734
Soptareanu Alex Avatar asked Aug 08 '16 08:08

Soptareanu Alex


People also ask

Can we convert object to array in JavaScript?

JavaScript Objects Convert object's values to array You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

What is a {} in JavaScript?

So, what is the meaning of {} in JavaScript? In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.

How do you convert an array of objects into an object object?

const arr = [{id:1,name:"aa"},{id:2,name:"bb"},{id:3,name:"cc"}]; We are required to write a JavaScript function that takes in one such array and returns an object of the object where the key of each object should be the id property.


1 Answers

You can use Object.keys() and map() to do 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 result = Object.keys(obj).map((key) => [Number(key), obj[key]]);  console.log(result);
like image 120
Nenad Vracar Avatar answered Sep 18 '22 14:09

Nenad Vracar