skip to Main Content

Convert an array object to separate separate object without object key. I like to

const arr = [ 
{ public_id: 'apple', secure_url: 'one' },
{ public_id: 'banana', secure_url: 'two' },
{ public_id: 'orange', secure_url: 'three' }
];

And i need to convert to

{ public_id: 'apple', secure_url: 'one' },
{ public_id: 'banana', secure_url: 'two' },
{ public_id: 'orange', secure_url: 'three' }

3

Answers


  1. The second one is not a valid data structure.

    You could however convert it to something like this:

    {
    0: { public_id: 'apple', secure_url: 'one' },
    1: { public_id: 'banana', secure_url: 'two' },
    2: { public_id: 'orange', secure_url: 'three' },
    }
    

    like this:

    const obj = {}
    arr.forEach((item, i) => {
      obj[i] = item
    })
    
    Login or Signup to reply.
  2. I did not get what you meant by saying seperate object without object key.
    It is comletely fine to store and reach objects in/from array, but if what you want is to iterate through objects in array then you can use built-in map() or forEach() functions.

    Login or Signup to reply.
  3. You can use destructuring to extract the array entries into individual variables:

    const arr = [
    { public_id: 'apple', secure_url: 'one' },
    { public_id: 'banana', secure_url: 'two' },
    { public_id: 'orange', secure_url: 'three' }
    ]
    
    let [a,b,c] = arr
    
    console.log(a)
    console.log(b)
    console.log(c)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search