将 "id" 添加到数组中每个对象的第一个 (JavaScript)

Add "id" to the first in each object in an array (JavaScript)

我可以将 "id" 添加到数组 "data":

中的每个对象

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

for(const key in data) {
  data[key]['id'] = key;
}

console.log(data);

但是"id"被添加到数组中每个对象的最后一个"data":

[
  { name: "John", age: 24, id: "0" },
  { name: "Marry", age: 18, id: "1" },
  { name: "Tom", age: 15, id: "2" }
]

我想要的结果是在下面将 "id" 添加到数组中每个对象的第一个 "data":

[
  { id: "0", name: "John", age: 24 },
  { id: "1", name: 'Marry', age: 18 },
  { id: "2", name: 'Tom', age: 15 }
]

有什么方法可以做到吗?

使用 "id" 创建数组 "newData""data" ]:

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: key,
    ...data[key]
  }

  newData.push(obj);
}

console.log(newData);

这是结果:

[
  { id: "0", name: "John", age: 24 },
  { id: "1", name: 'Marry', age: 18 },
  { id: "2", name: 'Tom', age: 15 }
]

另外,如果你想要 "id"Number 类型,使用 "Number()"。 =40=]:

const data = [
  { name: "John", age: 24 },
  { name: "Marry", age: 18 },
  { name: "Tom", age: 15 },
]

const newData = [];

for(const key in data) {

  const obj = {
    id: Number(key), // Here
    ...data[key]
  }

  newData.push(obj);
}

console.log(newData);

这是结果:

[
  { id: 0, name: "John", age: 24 },
  { id: 1, name: 'Marry', age: 18 },
  { id: 2, name: 'Tom', age: 15 }
]