I currently have two different iterations in my code:
For objects (snippet 1):
for (let key in object) {
if (object.hasOwnProperty(key)) {
// perform actions with key and object[key]
}
}
For arrays (snippet 2):
for (let i = 0, length = array.length; i < length; i++) {
// perform actions with i and array[i]
}
I want to simplify my code by using a single function for both objects and arrays (snippet 3):
let keys = Object.keys(objOrArray);
for (let i = 0, count = keys.length; i < count; i++) {
// perform actions with keys[i] and objOrArray[keys[i]]
}
I am aware that snippet 3 works well for objects, but will it also work as expected for arrays, replacing both snippets 1 and 2? Will snippet 3 ensure key order (starting from index 0) in all browsers (at least those supporting Object.keys)?
[edit] I am planning to use this specifically for deep merging of objects. My current code is complex, with three branches at each level depending on the type (array, object, or other).