Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 999
firasKoubaa Avatar asked Oct 09 '18 17:10

firasKoubaa


People also ask

How do you turn an array of strings into an object?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied!

How do I turn a string array into an array?

To convert a string to a char array, we can use the toCharArray() function. Detailed Procedure: Get the string. Call the toCharArray() method and store the character array returned by it in a character array.

Can we convert string to array in JS?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

How do you turn a string into an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');


1 Answers

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

myArray = myArray.map((str, index) => ({ value: str, id: index + 1 }));
like image 196
Pointy Avatar answered Oct 07 '22 18:10

Pointy