Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.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 使用嵌套数组和对象遍历对象数组以添加我自己的对象_Javascript_Arrays - Fatal编程技术网

Javascript 使用嵌套数组和对象遍历对象数组以添加我自己的对象

Javascript 使用嵌套数组和对象遍历对象数组以添加我自己的对象,javascript,arrays,Javascript,Arrays,我有一个嵌套对象和数组的数组: const myArr = [ { workoutName: "workout1", exercises: [ { exerciseName: "Bench Press", sets: [ { // some props and vals }, ] }, {

我有一个嵌套对象和数组的数组:

const myArr = [
  {
    workoutName: "workout1",
    exercises: [
      {
        exerciseName: "Bench Press",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      {
        exerciseName: "Deadlift",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      {
        exerciseName: "Squat",
        sets: [
          {
          // some props and vals
          },
        ]
      },
      // more exercises
    ]
  }
]

const compareVal = "Deadlift";
const mySetObj = {//some data}
我想遍历对象的exerces数组,并将每个对象的
exerciseName
值与
compareVal
进行比较,以获得匹配。如果匹配,我希望能够将
myObj
作为值添加到该对象的
集合
数组中。每个
exerciseName
值都是唯一的,因此在找到匹配项后,不必迭代所有练习


有什么方法可以优雅地实现这一点吗?

似乎一个数组
查找方法就足够了。注意,在这个解决方案中,我们在
myArr
数组上使用
forEach
循环,因为似乎您可能希望对每个例程都这样做

myArr.forEach(例程=>{
const ex=routine.exercises.find(e=>e.exerciseName===compareVal);
ex.set.push(mySetObj);
})
更新:由于您只需要将其用于
myArr[0]
,因此可以简化如下:

const ex=myArr[0]。exerces.find(e=>e.exerciseName==compareVal);
ex.set.push(mySetObj);
现在它开始工作了:

const myArr=[
{
工作名称:“工作1”,
练习:[
{
练习名称:“台式压力机”,
设置:[
{
//一些道具和VAL
},
]
},
{
练习名称:“死亡提升”,
设置:[
{
//一些道具和VAL
},
]
},
{
练习名称:“下蹲”,
设置:[
{
//一些道具和VAL
},
]
},
//更多的练习
]
}
]
const compareVal=“Deadlift”;
const mySetObj={some:“data”};
const ex=myArr[0]。exerces.find(e=>e.exerciseName==compareVal);
ex.set.push(mySetObj);

console.log(myArr)
它看起来像是
myArr
本身就是一个数组。您是否需要为每个训练例程执行此操作,或者仅为
myArr[0]
?仅为myArr[0],阵列将不会有多个训练例程。好的,我将更新我的答案