如何使用JavaScript数组映射方法编写循环代码

时间:2019-09-10 06:40:30

标签: javascript dictionary for-loop

这是我用javascript中的for循环编写的代码

var data = [{id: "1",LinkTitle: "a1", SubCategories: [{ id: "12", 
                                                        LinkTitle: "b1",
                                                        SubCategories: []
                                                     }]
    },
    {
        id: "2",
        LinkTitle: "l1",
        SubCategories: [
            {
                id: "21",
                LinkTitle: "l2",
                SubCategories: []
            },
            {
                id: "22",
                LinkTitle: "aa",
                SubCategories: []
            }
        ]
    }
];
var cat = [];
var x = ["l1", "l2"];
for (let i = 0; i < x.length; i++) {
    cat[i] = data.find(e => e.LinkTitle == x[i]);
    if (cat[i]) {
        data = cat[i].SubCategories;
    }
}

有什么方法可以从此代码中删除for循环,并用数组映射方法替换它

1 个答案:

答案 0 :(得分:0)

这是可能,只需将找到的项目保存在变量中,然后在回调的末尾将其返回:

var data = [{
    id: "1",
    LinkTitle: "a1",
    SubCategories: [{
      id: "12",
      LinkTitle: "b1",
      SubCategories: []
    }]
  },
  {
    id: "2",
    LinkTitle: "l1",
    SubCategories: [{
        id: "21",
        LinkTitle: "l2",
        SubCategories: []
      },
      {
        id: "22",
        LinkTitle: "aa",
        SubCategories: []
      }
    ]
  }
];
var x = ["l1", "l2"];
const cat = x.map((linkTitleToFind) => {
  const result = data.find(e => e.LinkTitle == linkTitleToFind);
  if (result) {
    data = result.SubCategories;
  }
  return result;
});
console.log(cat);

也就是说,.map内部的重新分配很奇怪。