skip to Main Content

If I have an array that looks like:

arr =[ { id: ‘f794’,label: ‘Blue Bird’ } ]

how do I give the element of it a key so I get

arr =["myKey":{ id: 'f794',label: 'Blue Bird' } ]

I have tried several different ways, like

arr[0]= '"myKey"' + ":" + arr[0]

which gives me

[ "myKey:[object Object]" ]

How do I get arr =["myKey":{ id: 'f794',label: 'Blue Bird' } ]

Thanks

2

Answers


  1. You can do :

    arr = arr.map((element) => {
       return ({"myKey" : element})
    })
    

    With perhaps a specific key for each element depending on what you want to do with it.

    Login or Signup to reply.
  2. Here is how:

    let arr = [{ id: 'f794',label: 'Blue Bird' }];
    
    arr = arr.map( myKey => {
       return { myKey };
    });
    
    console.log( arr );

    Or the shorthand equivalent:

    let arr = [{ id: 'f794',label: 'Blue Bird' }];
    
    arr = arr.map( myKey => ({ myKey }) );
    
    console.log( arr );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search