如何从数组内的数据创建对象中的键?

Zum*_*mmi 1 javascript arrays loops object

如何从数组内的数据创建对象中的键?

function createIt(data) {
  var obj = {};
  for (i of data) {
    obj["fruit"] = i;
  }
  return [obj];
}

var list = ["orange", "apple", "pineapple"];
console.log(createIt(list));
Run Code Online (Sandbox Code Playgroud)
在我上面的代码中,obj.fruit唯一显示一个值,我想创建这样的东西:

[
  { fruit: "orange" },
  { fruit: "apple" },
  { fruit: "pineapple" }
]
Run Code Online (Sandbox Code Playgroud)

qui*_*mmo 5

映射输入数组并使用key水果返回一个对象数组

var list = ["orange", "apple", "pineapple"];
console.log(list.map(i => ({ fruit: i })));
Run Code Online (Sandbox Code Playgroud)

这里有一个for循环返回一个新数组,即使我不知道为什么你不想使用map数组方法:

const list = ["orange", "apple", "banana"];

const newList = [];
for (let i = 0; i < list.length; i++) {
  newList.push({
    fruit: list[i]
  });
}

console.log(newList);
Run Code Online (Sandbox Code Playgroud)

这里有一个for循环更改输入数组,即使再次,也不知道为什么你不能使用map数组方法:

const list = ['orange', 'banana', 'apple'];

for (let i = 0; i < list.length; i++) {
  list.splice(i, 1, {
    fruit: list[i]
  });
}

console.log(list);
Run Code Online (Sandbox Code Playgroud)

回到原始代码:

function createIt(data){
  var obj = {};
  for(i of data){
    obj["fruit"]= i
  }
  return [obj]
}
var list = ["orange", "apple", "pineapple"];
console.log(createIt(list))
Run Code Online (Sandbox Code Playgroud)

您确实创建了一个对象,并始终覆盖fruit键的值.您应该创建一个数组,将对象推入循环中的数组,然后返回数组,如下所示:

function createIt(data) {
  var objs = [];
  for (i of data) {
    objs.push({fruit: i});
  }
  return objs;
}
var list = ["orange", "apple", "pineapple"];
console.log(createIt(list))
Run Code Online (Sandbox Code Playgroud)