【问题标题】:How can i change object's item value in a loop in javascript?如何在javascript的循环中更改对象的项目值?
【发布时间】:2021-07-30 10:15:35
【问题描述】:

我有类别列表。每个类别都是这样的:

{
 id,
 name,
 info
}

我想在一个 http get 请求后遍历列表并更改吃的类别信息。 我已经搜索并阅读了类似的问题,但没有任何效果。信息总是有它的初始值

【问题讨论】:

标签: javascript node.js arrays object


【解决方案1】:

您可以使用forEach,如下所示:

arr.forEach(function(part, index) {
  this[index] = "hello world";
}, arr); // use arr as this

【讨论】:

【解决方案2】:

在下面的sn-p中:

  • 我只是循环遍历categories 数组,并在获取数据后更新info 属性。

注意:

  • 这里的一个常见错误可能是您在 async 任务完成之前记录了 categories 数组。

  • 因此,在下面的代码中,如果我将getData().then(() => console.log(categories)); 替换为getData(); console.log(categories);,那么我将看不到info 的更新值。

const categories = [
  {
    id: 1,
    name: "delectus aut autem",
    info: "not fetched",
    url: "https://jsonplaceholder.typicode.com/todos/1",
  },
  {
    id: 2,
    name: "quis ut nam facilis",
    info: "not fetched",
    url: "https://jsonplaceholder.typicode.com/todos/2",
  },
];

const getData = async () => {
  for (let cat of categories) {
    const res = await fetch(cat.url);
    const json = await res.json();
    cat.info = "fetched";
  }
};

getData().then(() => console.log(categories));

【讨论】:

  • @SalehRezaei 请检查这是否解决了您的问题,如果您有任何问题,请告诉我。
  • 谢谢,你的回答正是我需要的。
猜你喜欢
  • 2017-07-24
  • 2020-07-24
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多