简体   繁体   中英

'Undefined' bug in react native map function for object array

Object {
  "id": 172,
  "user_na": "User 1",
}
Object {
  "id": 173,
  "user_na": "User 2",
}
Object {
  "id": 174,
  "user_na": "User 3",
}
Object {
  "id": 175,
  "user_na": "User 4",
}

This is my array and I want to get each id and user_na for which I've used map function.

data.map((dataMapped) => {
   console.log(data.id);
   console.log(data.user_na);
});

But I'm getting an output like

undefined
undefined
undefined
undefined

I expect to see output like,

172
User 1
173
User 2
.........

My array [] name data which is a const . I'm extracting the info from SQLite database and pushing into data array, which gives me the above format

const data = [];

for (let i = 0; i < len; i++) {
     data.push(results.rows.item(i));
}

Since I'm new to asking questions on stackoverflow, I don't know how to properly ask

You haven't used dataMapped in your map.

data.map((dataMapped) => {
   console.log(dataMapped.id);
   console.log(dataMapped.user_na);
});

You have used wrong variable inside your loop. Please Replace "data.id" with "dataMapped.id" and "data.user_na" with "dataMapped.user_na"

data.map((dataMapped) => {
  console.log(dataMapped.id);
  console.log(dataMapped.user_na);
});

dataMapped is each single entity in your data array in your case

 data.map((dataMapped) => {
   console.log(dataMapped.id);
   console.log(dataMapped.user_na);
});

ex

arr=[{name:"1"},{name:"2"}]

arr.map((dataMapped)=>
{
console.log(dataMapped.name)
})

1
2

where dataMapped is object in that you required

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM