1

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.

1
  • 5
    Looks like a malformed array. Arrays shouldn't have name properties. Better to fix the code that generates it, so that you can then use standard array methods and index notation. Commented Aug 17, 2018 at 0:12

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir, for your response. I have tried it, but it still doesn't work.
0
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

enter image description here

1 Comment

Thank you sir, for your response. I have tried it, but it still doesn't work. Because myArray it's not look like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.