I have an object where two parameters hold arrays as their values. When I try to output the types of these values using the typeof
operator in a loop, for some reason, I always get a string
type instead of the actual array
value.
const add = "add"
const edit = "edit"
const required = {
user: [add, edit],
profile: [edit],
}
for (let p in required) {
console.log(p, typeof(p))
}
Output:
string
string
2
Answers
This is how you access the array (the value)-
Object[key]
which translates, in your case torequired[p]
.(The
typeof
function logsarrays
as'object'
)for...in
loop, you’re querying its keys.for...in
gives us the keys again.for...in
andfor...of
. Usingfor...of
gives us the values of the array. However, the original keys of the object are lost here. The question is whether we need them.for...of
, it’s inherently difficult to obtain the keys. However, if you useObject.entries()
instead ofObject.values()
to convert it into an array, the new array will contain both the keys and their values, which you can then retrieve within thefor...of
loop.Example with your object
More information
Object.keys()
– MDN DocsObject.values()
– MDN DocsObject.entries()
– MDN Docsfor...in
loop – MDN Docsfor...of
loop – MDN Docsconst [a, b] = ["first", "second"]
– MDN Docs