Reputation: 75
I'm trying to retrieve the value of "id" from a one-object-long array in React. (The data is coming from Firebase). I have tried every possible combination of code, but it always gives me back undefined (in Firefox).
So I have this array called "Original Data", and this is where I want to retrieve the "id" and store it in a variable. Then I tried to convert it into object by slicing to first element of arary (although I'm not sure if that's needed altogether). And then I'm trying to retrieve the id by calling the Object.id value, but it returns undefined.
I tried doing it with data.id
(thinking maybe it's Firebase data structure), but it also doesn't work.
My code:
console.log("OriginalData")
console.log(OriginalData)
const ConvertingToObject = {... OriginalData.slice(0)}
const RetrievingID = ConvertingToObject.id
console.log("Converting to Object")
console.log(ConvertingToObject)
console.log("Retrieving ID")
console.log(RetrievingID)
Console log:
**OriginalData **
Array [ {…} ]
0: Object { data: {…}, id: "100" }
length: 1
<prototype>: Array []
**Converting to Object**
Object { 0: {…} }
0: Object { data: {…}, id: "100" }
<prototype>: Object { … }
**Retrieving ID **
undefined
Upvotes: 1
Views: 63
Reputation: 406
As you can see while you are try to convert array of object into object, Key of array change itself into key of object. For example:
let arrayOfObj = [{data: {
"name": "naruto"
}, id: 123}]
let convertToObj = {...arrayOfObj.slice(0)}
while consoling the data convertToObj we can see log as:
{ '0': { data: { name: 'naruto' }, id: 123 } }
See the key value '0'. So to access id from that you will need to do something like this:
console.log(convertToObj['0'].id)
Or, Incase if do not want to change it to object then you can do like this:
console.log(arrayOfObj[0].id)
Upvotes: 1