While attempting to create a new array of objects from an existing array that I am iterating through, I seem to only retain the last value. I understand why this is happening, but I am unsure of the best approach to achieve the desired outcome.
var existingThing = ["one","two","three"];
var thingtoAdd = {};
var newthing = [];
for (var i = 0; i < existingThing.length; i++) {
thingtoAdd.key = existingThing[i];
thingtoAdd.value = existingThing[i];
thingtoAdd.selected = "true";
newthing.push(thingtoAdd);
}
console.log(JSON.stringify(newthing));
The resulting output is:
[{"key":"three","value":"three","selected":"true"},
{"key":"three","value":"three","selected":"true"},
{"key":"three","value":"three","selected":"true"}]