Cannot push item from an array into JSON objects in another array

I have a while loop to push an item into an array. For example, there are three items in an array. I need to push them into a JSON object.

["item1", "item2", "item3"] -> [{"path": "item1"}, {"path": "item2"}, {"path": "item3"}]

I tried the following code:

var i = 0;
var array = ["item1", "item2", "item3"];
var obj = [{}];
while (i < array.length) {
obj[i]["path"] = array[i];
i++
}

It gives me this error: Cannot set property 'path' of undefined
Which is supposed to push items from the array into an array of JSON objects. Sorry if I don’t make any sense because I am confused.

The example result is a list of objects, but your code is trying to create an object instead of a list.

You probably want to start with an empty list [] instead of a list of one empty object

var mylist = []

Here is where the push should be, like you mentioned in the topic, the new object can be created at the same time

mylist.push({new object here})
1 Like

Thanks!