I have an array of object, I want to get the objects from 'Seconditem' in my array. I have tried using object.keys but its not working. Code is below https://stackblitz.com/edit/angular-pmfjux?file=src%2Fapp%2Fapp.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
ngOnInit() {
const sampleArray = [
{
mainitem: "My item 1",
Seconditem: {
createddate: "30-01-02",
enddate: "30-01-03"
}
}
];
// console.log(sampleArray)
Object.keys(sampleArray.Seconditem).forEach(key => {
console.log(key);
});
}
}
you can not do sampleArray.secondItem as sampleArray is an array not an object
you have to iterate over array to get the keys of every object in the array
sampleArray.forEach(x => {
Object.keys(x.Seconditem).forEach(key => {
console.log(key, ': ', x.SecondItem[key]);
});
});
i have update this link to print the object values https://stackblitz.com/edit/angular-cckvqe?file=src%2Fapp%2Fapp.component.ts
well, your sampleArray is an array and not an object so you first need to specify an index, you just need to add [0] as in:
const item = {};
Object.keys(sampleArray[0].Seconditem).forEach(key => {
item[key] = sampleArray[0].Seconditem[key];
});
console.log({ item });
(anyway I am not sure why that needs to be array, maybe you should just convert it to a normal object, or if it's an array because you will also have to add other objects like the one already there then instead of [0]
you will need a [idx]
where idx
is an index you loop through)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.