Reputation: 337
In JavaScript, it is possible to loop through an object using the Object.keys
method.
With this, I can loop the person
Object as:
let person: {
name: "John",
lastName: "Doe",
age: 31,
}
for (let key of Object.keys(person)) {
console.log(person[key])
}
Now, how is it possible to do this if the person
has arrays as properties?
person: {
name: "John",
lastName: "Doe",
age: 31,
address: [{
street: "A Street Name",
number: 190,
apartment: 13
}]
}
Upvotes: 1
Views: 93
Reputation: 38209
Try to use Object.entries
:
Object.entries(object).forEach(([k, v]) => {
if (Array.isArray(v)) {
let keys = Object.keys(...v);
console.log(keys)
}
});
An example:
let object = {
array: [
{
prop1: 1,
prop2: 2,
prop3: 3
}]
}
Object.entries(object).forEach(([k, v]) => {
if (Array.isArray(v)) {
let keys = Object.keys(...v);
console.log(keys)
}
});
Upvotes: 0
Reputation: 11604
It's not very clear what your're trying to accomplish, but going off your example, you can iterate prop1
, prop2
, prop3
values:
let object = {
array: [{
prop1: 1,
prop2: 2,
prop3: 3
}]
};
for (key in object.array[0])
console.log(key, object.array[0][key]);
Upvotes: 2