Reputation: 159
I have an array coming from api which I am storing in a state, I want to store that array in another state as a List of objects where each array element would be a value with some Id
i-e
original array = ["value1","value2"....,"value(n)"]
converted to List = [{value: "value1", id: 1}, {value: "value2", id: 2}]
Upvotes: 0
Views: 134
Reputation: 167250
What you can do in simple terms is using a map()
function. Your code should be something like this:
(value, id) => ({ value, id: id + 1 })
And here's the working snippet:
const arr = ["value1","value2","value(n)"];
const obj = arr.map((value, id) => ({value, id}));
console.log(obj);
If you want the values to be one-indexed, you can change it this way:
const arr = ["value1", "value2", "value(n)"];
const obj = arr.map((value, id) => ({
value,
id: id + 1
}));
console.log(obj);
Upvotes: 1