I have an array that isn't normal. Which can be accessed using index.
For example: I have an array and if I want to access it, I only need to use myArray[0] or myArray.name.
But, my array below is different:
get Index Of Array Using JavaScript
[]
name: Array(4)
0 : {_id: "5b6bad0d7e9f754ff8aebd66", username: "tisufa", password: "12345"}
1 : {_id: "5b6bad367e9f754ff8aebd67", username: "titus", password: "88888"}
2 : {_id: "5b6c0f2c5978404d7431d589", username: "titus", password: "8888"}
3 : {_id: "5b7103cdabcb573894cc1875", username: "nn", password: "22222"}
I tried to access myArray['name'] or myArray.name, but I can't do it.
I have tried to use:
for(let key in myArray){
console.log(key);
}
but, I also can't access the key of the array. I got the information undefined
I beg for your help.
Thank you in advance.
2 Answers 2
myArray.name[0]
For some reason, you created an array and then created another array inside that array. I was able to reproduce what you did with this code:
let myArray = []
myArray['name'] = []
Find where you're doing this and fix it, or make your outer array an object:
let myArray = {} // This is an object
myArray['name'] = []
In both cases, you can access and loop through your array like so:
console.log(myArray.name) // print entire array
for(let i in myArray.name)
console.log(myArray.name[i]) // print each element in array
1 Comment
let arr_obj = [
{_id: "5b6bad0d7e9f754ff8aebd66", username: "tisufa", password: "12345"},
{_id: "5b6bad367e9f754ff8aebd67", username: "titus", password: "88888"},
{_id: "5b6c0f2c5978404d7431d589", username: "titus", password: "8888"},
{_id: "5b7103cdabcb573894cc1875", username: "nn", password: "22222"},
];
for(let [index,data] of arr_obj.entries()){
console.log("index:",index,"data:",data);
}
ES6 for of and entries
nameproperties. Better to fix the code that generates it, so that you can then use standard array methods and index notation.