I’m trying to create an object with dynamic keys with key ID and value as a name from a string that I’m getting through API.
Below is my API
["PHP", "Project Management", "PHP dynamic website", "Ecommerce", "Magento", "Magento Websites"]
I want to convert it to following response
[
{ id: 0, name: "PHP" },
{ id: 1, name: "Project Management" },
{ id: 2, name: "PHP dynamic website" },
{ id: 3, name: "Ecommerce" }
]
5
Answers
Just use a
forEach
loop, and use the iterator as the key:There no dynamic keys in here tho, all your objects and their keys look the same… Simply use the array.forEach() method to loop on all array values and push them into object into a new array:
Easy as that.
You can map each name to an object which uses the index as the
id
and the value as thename
property:Considering your usecase: Assuming newArr is the type of array you want
// ar is the initial array
I used traditional way. hope you are looking for this one.