Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向深度嵌套的对象数组添加唯一ID的最有效方法_Javascript_Arrays_Loops_Ecmascript 6_Javascript Objects - Fatal编程技术网

Javascript 向深度嵌套的对象数组添加唯一ID的最有效方法

Javascript 向深度嵌套的对象数组添加唯一ID的最有效方法,javascript,arrays,loops,ecmascript-6,javascript-objects,Javascript,Arrays,Loops,Ecmascript 6,Javascript Objects,我需要将ID添加到对象数组中: 例如: 在本例中,我需要向训练数组和深度嵌套的区域数组添加ID。 我提出了通过每个阵列进行映射的解决方案: const idMappings = workouts.map((workout) => { const workoutIdMapping = workout.id ? workout : { ...workout, id: uuid.v4() }; // if there is already an id just return the ob

我需要将ID添加到对象数组中: 例如:

在本例中,我需要向
训练
数组和深度嵌套的
区域
数组添加ID。 我提出了通过每个阵列进行映射的解决方案:

const idMappings = workouts.map((workout) => {
    const workoutIdMapping = workout.id ? workout : { ...workout, id: uuid.v4() }; // if there is already an id just return the object -- otherwise generate a random id
    const areasIdMapping = workoutIdMapping.areas.map((area) => {
        return area.id ? area : { ...area, id: uuid.v4() }; // if there is already an id just return the object -- otherwise generate a random id
    });
    return { ...workoutIdMapping, areas: areasIdMapping }; // finally return the updated values with ids
});
这将正确地返回以下ID为的区域:

const workouts = [
  { 
    id: "0000-0000-4e6b-9f24-f8e1f2402a9b"
    type: "walk"
    areas: [
      {
        id: "0000-1111-4e6b-9f24-f8e1f2402a9b"
        location: 'park'
        day: 'Sunday'
      },
      {
        id: "0000-2222-4e6b-9f24-f8e1f2402a9b"
        location: 'beach'
        day: 'Monday'
      }
    ],
    exercise: true
  },
  { 
    id: "1111-0000-4e6b-9f24-f8e1f2402a9b"
    type: "run"
    areas: [
      {
        id: "1111-1111-4e6b-9f24-f8e1f2402a9b"
        location: 'gym'
        day: 'Saturday'
      },
      {
        id: "1111-2222-4e6b-9f24-f8e1f2402a9b"
        location: 'track'
        day: 'Sunday'
      }
    ],
    exercise: true
  }
]

这个算法工作正常,但是有没有更有效的方法来解决这个问题?多次映射不是解决这个问题的有效方法吗?也许我可以使用更好的ES6函数?

也许你可以在这里使用递归。像这样:

function setIds (arr) {
  arr.forEach(item => {
    item.id = uuid.v4()
    if (item.areas && item.areas.length > 0) {
      setIds(item.areas)
    }
  })
}

setIds(workouts)

也许你可以在这里使用递归。像这样:

function setIds (arr) {
  arr.forEach(item => {
    item.id = uuid.v4()
    if (item.areas && item.areas.length > 0) {
      setIds(item.areas)
    }
  })
}

setIds(workouts)

如果这是一个有效的解决方案,也许更好的地方是谢谢你,我将这个问题标记为版主干预,以便在每个对象属性都必须使其语法正确后移到Code ReviewCommas?如果这是一个有效的解决方案,也许更好的地方是谢谢你,我将这个问题标记为版主干预,以便在每个对象属性都是语法正确所必需的之后,将其移动到CodeReviewCommas?