Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split a js object into an array of key-value pairs?

Let's say I have an object like this:

var myObject = {
   X:1,
   Y:2,
   Z:3
}

Let's say I want to create a for loop to process each property on the object. The code below is just intended to be some pseudocode to communicate what I'm looking to do:

var properties = myObject.split();
for(var i = 0; i < properties.length; i++)
{
   var x = properties[i][key];
   var y = properties[i][value]
}

Can you recommend some code I can use to accomplish this in Javascript/TypeScript?

like image 874
user8570495 Avatar asked Aug 31 '25 22:08

user8570495


2 Answers

You could use the Object.entries function to get all the key and value pairs as an array of arrays:

Object.entries(myObject);

Which would return:

[['X', 1], ['Y', 2], ['Z' 3]]

And you could iterate through them:

for(const [key, value] of Object.entries(myObject)) {
  console.log(key, value);
}

Which would log out:

X 1
Y 2
Z 3

Do note that this is a relatively new feature with no support on IE nor Opera. You can use the polyfill from MDN or use any of the other methods (for…in with hasOwnProperty, Object.keys, etc.).

like image 53
Andrew Li Avatar answered Sep 03 '25 14:09

Andrew Li


var arr = {
        X:1,
        Y:2,
        Z:3
    };


Object.keys(arr).map(key => { console.log(key, arr[key]) })
like image 40
Chandrakant Thakkar Avatar answered Sep 03 '25 13:09

Chandrakant Thakkar