Home > Mobile >  Is it possible to convert an array of single object into an array of multiple object with keys in ja
Is it possible to convert an array of single object into an array of multiple object with keys in ja

Time:09-06

So, I have this array like this:

const arrayItem = [
0: 'item1', 'item2', 'item3', 'item4'
]

And I would like to create something like this out of it:

const updatedArray = [
   {0: 'item1'},
   {1: 'item2'},
   {2: 'item3'},
   {3: 'item4'},

 ]

See image for the array from my console.log enter image description here Is there a way around this?

CodePudding user response:

So based on your image you have:

const arrayItem = ['string1, string2, string3, string4'];

you need to extract the first item from the array:

const longString = arrayItem[0];
const listOfStrings = longString.split(',');
const listOfObjects = listOfStrings.map((item, index)=>{ 
return {[index]: item}
});

CodePudding user response:

I think you are looking for Object.values(object) :

const arrayItems = [{0: ['item1', 'item2', 'item3', 'item4']}];

Object.values(arrayItems[0]);

enter image description here

  • Related