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?

1
  • 1
    Object.keys(myObject).forEach(key => { console.log(key, myObject[key]) }) Commented Dec 20, 2017 at 4:34

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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


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

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.