Map the input array and get back an array of objects with the key fruit
var list = ["orange", "apple", "pineapple"];
console.log(list.map(i => ({ fruit: i })));
Here a for loop returning a new array, even if I have no idea why you don't want to use map method of arrays:
const list = ["orange", "apple", "banana"];
const newList = [];
for (let i = 0; i < list.length; i++) {
newList.push({
fruit: list[i]
});
}
console.log(newList);
Here a for loop changing the input array, even if again, no idea why you can't use map method of arrays:
const list = ['orange', 'banana', 'apple'];
for (let i = 0; i < list.length; i++) {
list.splice(i, 1, {
fruit: list[i]
});
}
console.log(list);
Back to your original code:
function createIt(data){
var obj = {};
for(i of data){
obj["fruit"]= i
}
return [obj]
}
var list = ["orange", "apple", "pineapple"];
console.log(createIt(list))
You do create a single object, and you always override the value of the fruit key. You should create an array, push the objects into the array in the loop, and then return the array, as below:
function createIt(data) {
var objs = [];
for (i of data) {
objs.push({fruit: i});
}
return objs;
}
var list = ["orange", "apple", "pineapple"];
console.log(createIt(list))
var res = list.map(fruit => ({fruit}))obj["fruit"]. Add to an array in each iteration instead.