JS : Convert Array of Strings to Array of Objects

2020-01-25 11:36发布

问题:

i have this array of strings :

let myArray : ["AA","BB" , "CC" ...]

I want to convert it to an array of objects:

myArray  = [{"id":1 , "value": "AAA"},{"id":2 , "value": "BBB"},{"id":3 , "value": "CCC"}...]

I ve trie with "let for":

for (let obj of  ListObj) {
      let resObj = {};
      resObj ['value'] = obj  ;
      equipment = resObj ;
}

And with map :

ListObj.map(obj => { 'value' = obj })

Suggestions ?

回答1:

You can use .map() for this. It passes the index into the callback.

myArray = myArray.map((str, index) => ({ value: str, id: index + 1 }));