简体   繁体   中英

JS : Convert Array of Strings to Array of Objects

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM