1

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

1 Answer 1

1

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

1 Comment

hi! I have tried that before, and when I do this, all of my arrays return as empty. (In the code I get data from Firebase -> make some calculations in the client -> get "OriginalData" as a result). So normally I have a list of arrays in my console log and everything works. As soon as I try the above (both with and without converting to object), all of the arrays return as empty...

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.