I have an array like this:
console.log(this.props.countrysideTypes)
[{…}]
0:
field: Array(8)
0: "Wood"
1: "Grain"
2: "Grain"
3: "Grain"
4: "Stone"
5: "Iron"
6: "Grain"
7: "Grain"
length: 8
__proto__: Array(0)
id: "-MHLWLm8bFRE2_1aahWk"
userId: "lPqZ8Oj90Se2qBEIzTJq1OSfbo62"
__proto__: Object
length: 1
__proto__: Array(0)
now i want to reach eg the first item "Wood"
i tried
console.log(this.props.countrysideTypes[0])
that gave me:
{field: Array(8), userId: "lPqZ8Oj90Se2qBEIzTJq1OSfbo62", id: "-MHLWLm8bFRE2_1aahWk"}
field: Array(8)
0: "Wood"
1: "Grain"
2: "Grain"
3: "Grain"
4: "Stone"
5: "Iron"
6: "Grain"
7: "Grain"
length: 8
__proto__: Array(0)
id: "-MHLWLm8bFRE2_1aahWk"
userId: "lPqZ8Oj90Se2qBEIzTJq1OSfbo62"
__proto__: Object
but i cant get the deeper nested item. I tried
console.log(this.props.countrysideTypes[0].field) //TypeError: Cannot read property 'field' of undefined console.log(this.props.countrysideTypes[0][0]) //TypeError: Cannot read property 'field' of undefined console.log(this.props.countrysideTypes[0].field[0]) //TypeError: Cannot read property 'field' of undefined console.log(this.props.countrysideTypes.field) // undefined
This should work
console.log(this.props.countrysideTypes[0].field[0])
You have an array with Object in it. In the Object you have the array yu would like to access and it is assigned to property field.
Thanks for your kind help! The data comes from firebase realtime Database. It seems it was just nested too deeply. Finally it worked like so:
let objectArray = Object.entries(this.props.countrysideTypes);
let types = [];
objectArray.forEach(([key, value]) => {
types = value.field;
});
console.log(types[0]); //"Wood"
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.