-2

This may be a very simple question, but I have not found the answer in the last hour. I have the following array, which always contains a single object in index 0. For convenience in later use, I want to remove the object from the array and store it directly as a single object. I.e. the object should no longer be wrapped in the array.

Current Status: Array

Array(1)
0:
   bio: "Test"
   id: 2
   image: "http://localhost:8000/media/default.jpg"
   user: 2

Target: Object

Object
   bio: "Test"
   id: 2
   image: "http://localhost:8000/media/default.jpg"
   user: 2
dan_boy
  • 1,735
  • 4
  • 19
  • 50
  • It sounds like you have some incorrect mental model of how objects are stored in memory (I.e. the object should no longer be wrapped in the array.) Object is never wrapped in anything. Array only stores a reference to this object. But you are free to have as many refs for a object as you need `const obj = array[0]` – Yury Tarabanko Jul 09 '20 at 15:13
  • What is the use case? As you can see there are many options for this. In your case, extracting the first item using spread works, but for example if this object has a nested property, and you change it even spreading does not work and you mutate the original object. So, the use case is important here since there is a `reactjs` tag in the question. – devserkan Jul 09 '20 at 15:14

1 Answers1

2

You can just assign the first value of the array to a variable. Remember, the array just stores a reference to the object, this reference can be stored in a variable instead and interacted with that way.

var arr = [
  {
    bio: "Test",
    id: 2,
    image: "http://localhost:8000/media/default.jpg",
    user: 2
  }   
]

var obj = arr[0] // obj stores a reference to the object in arr

console.log(obj)

If you want to work with the object outside of the array without modifying the object in the array, you can "duplicate" it with the spread operator.

var arr = [
  {
    bio: "Test",
    id: 2,
    image: "http://localhost:8000/media/default.jpg",
    user: 2
  }   
]

var obj = {...arr[0]} // obj stores a reference to an object identical to arr[0]

console.log(obj)
AJ_
  • 1,455
  • 8
  • 10