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?
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.).
var arr = {
X:1,
Y:2,
Z:3
};
Object.keys(arr).map(key => { console.log(key, arr[key]) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With