【问题标题】:Add incrementing ID to obj in array将递增 ID 添加到数组中的 obj
【发布时间】:2018-02-23 11:11:07
【问题描述】:

尝试为数组中的每个对象添加一个 ID。如果 id 已经存在,则 id 将递增 1,试图让自动递增函数运行。问题是,使用这个函数,每个对象要么在 for each 语句内运行 for 循环时获得相同的 ID,要么如果循环在外部运行,我将无法读取 obj.id of undefined

function addId(arr, obj) {
  obj.id;
  arr.forEach(function(obj) {
    obj.id = 0;
    return obj.id;
  });
  for(var i = 0; i <= arr.length; i++) {
    if(obj.id == obj.id) obj.id++;
  }
};

【问题讨论】:

  • forEach 将当前元素作为回调中的参数。
  • 你能添加arr的样子吗?

标签: javascript arrays object for-loop foreach


【解决方案1】:

您的代码存在一些问题。首先obj.id; 什么都不做。所以你应该摆脱它。同样在forEach 内部,您将值0 作为ID 分配给每个对象,但是在第二个循环中,您正在检查作为参数传入的obj 的ID 是否与本身,因此检查将始终产生true,然后您将增加传入obj 的ID。

因此,在将数组的 id 属性设置为 0 后,您永远不会操作数组中的对象。

您可以使用索引作为 id 的值。

此外,如果需要,您可以考虑使用 Object.assign 之类的东西来防止更改数组中的原始对象。

function addId(arr) {
  return arr.map(function(obj, index) {
    return Object.assign({}, obj, { id: index });
  });
};

// test
const input = [ { a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
const output = addId(input);

console.log(output);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2021-08-07
    • 2013-08-18
    • 2021-03-10
    • 2020-10-15
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多