4

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?

user8570495
  • 1,645
  • 5
  • 19
  • 29

5 Answers5

6

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

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
1

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


Object.keys(arr).map(key => { console.log(key, arr[key]) })
0

Here is the solution.

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

for (var key in arr) {
    if (arr.hasOwnProperty(key)) {
        console.log(key + " -> " + arr[key]);
    }
}

Another way you can do is

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


Object.keys(arr).forEach(key => { console.log(key, arr[key]) })
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
0

Best practice is typically using Object.keys().

var keys = Object.keys(myObject);
for(var i = 0; i < keys; i++) {
  var key, value;
  key = Object.keys[i];
  value = myObject[key];

  // .. do something else ..
}
SISYN
  • 2,209
  • 5
  • 24
  • 45
0

You can do this Object keys method. Create a custom function and add it to the prototype of the Object like,

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

Object.prototype.mySplit = function() {
  return Object.keys(this).map((key) => {
    return {
      key: key,
      value: this[key]
    };
  });
}

var properties = myObject.mySplit();
for (var i = 0; i < properties.length; i++) {
  console.log(properties[i]['key'], properties[i]['value']);
}
vibhor1997a
  • 2,336
  • 2
  • 17
  • 37