【问题标题】:Parse array of objects recursively and filter object based on id递归解析对象数组并根据 id 过滤对象
【发布时间】:2017-07-20 12:08:31
【问题描述】:

我有这个对象数组:getCategory(变量)

[
  {
    "id": "20584",
    "name": "Produits de coiffure",
    "subCategory": [
      {
        "id": "20590",
        "name": "Coloration cheveux",
        "subCategory": [
          {
            "id": "20591",
            "name": "Avec ammoniaque"
          },
          {
            "id": "20595",
            "name": "Sans ammoniaque"
          },
          {
            "id": "20596",
            "name": "Soin cheveux colorés"
          },
          {
            "id": "20597",
            "name": "Protection"
          },
          {
            "id": "20598",
            "name": "Nuancier de couleurs"
          }
        ]
      },
      {
        "id": "20593",
        "name": "Soins cheveux",
        "subCategory": [
          {
            "id": "20594",
            "name": "Shampooing"
          },
          {
            "id": "20599",
            "name": "Après-shampooing"
          },
          {
            "id": "20600",
            "name": "Masques"
          },

我尝试了我可以在 stackoverflow 中搜索的所有内容..

让我们说在这个数组上我想递归地获取具有指定 id 的对象 .. 像 20596 它应该返回

{
            "id": "20596",
            "name": "Soin cheveux colorés"
          }

我做的逻辑是这样的:

var getSubcategory = getCategory.filter(function f(obj){
        if ('subCategory' in obj) {
            return obj.id == '20596' || obj.subCategory.filter(f);
        }
        else {
            return obj.id == '20596';
        }
    });

不知道还能做什么。 谢谢

PS:我不在浏览器中使用它,所以我不能使用任何库。只是服务器端,没有其他库。 find 不工作所以我只能使用filter

【问题讨论】:

    标签: javascript node.js rhino


    【解决方案1】:

    您需要返回找到的对象。

    function find(array, id) {
        var result;
        array.some(function (object) {
            if (object.id === id) {
                return result = object;
            }
            if (object.subCategory) {
                return result = find(object.subCategory, id);
            }
        });
        return result;
    }
    
    var data = [{ id: "20584", name: "Produits de coiffure", subCategory: [{ id: "20590", name: "Coloration cheveux", subCategory: [{ id: "20591", name: "Avec ammoniaque" }, { id: "20595", name: "Sans ammoniaque" }, { id: "20596", name: "Soin cheveux colorés" }, { id: "20597", name: "Protection" }, { id: "20598", name: "Nuancier de couleurs" }] }, { id: "20593", name: "Soins cheveux", subCategory: [{ id: "20594", name: "Shampooing" }, { id: "20599", name: "Après-shampooing" }, { id: "20600", name: "Masques" }] }] }];
      
    console.log(find(data, '20596'));
    console.log(find(data, ''));

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2022-01-12
      • 1970-01-01
      • 2018-12-25
      • 2021-03-21
      • 2022-01-23
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多