在对象

时间:2017-08-18 11:19:43

标签: javascript angularjs

我有一些这样的对象


    $scope.categories = [
    {
        value: 'One',
        id: 1,
        childs: [
          {
            value: 'Two',
            id : 2,
            childs: [
              {
                value: 'Three',
                id: 3
              },
              {
                value: 'Four',
                id: 4           
              }
            ]
          },
          {
            value: 'Five',
            id: 5
          },
          {
            value: 'Six',
            id: 6,
            childs: [
              { 
                value: 'Seven',
                id: 7
              },
              {
                value: 'Eight',
                id: 8
              }
            ]        
          }
        ]
      },
      {
        value: 'Nine',
        id: 9
      }
    ];

如果我知道id,我如何获得元素和父母? 我使用angularjs,但它并没有帮助我解决我认为的任务......

2 个答案:

答案 0 :(得分:0)

使用此功能可以平整阵列:

function flat(o, parent) {
  let res = []
  o.forEach(child => {
    child.parent = parent
    res.push(child)
    if (child.childs) {
      Array.prototype.push.apply(res, flat(child.childs, child.id))
    }
  })

  return res
}

用法:

let categories = [
    {
        value: 'One',
        id: 1,
        childs: [
          {
            value: 'Two',
            id : 2,
            childs: [ /* ... */ ]
          },
          /* ... */
        ]
    ];

let flat_categories = flat(categories)

结果:

Array[9]: [
  {
     value: 'One',
     id: 1,
     childs: [/*...*/],
     parent: undefined
  }, {
     value: 'Two',
     id: 2,
     childs: [/*...*/],
     parent: 1
  }, 
  ...
]

您现在可以轻松找到好身份证及其父母

答案 1 :(得分:0)

正如Icycool所说,你需要递归搜索你的收藏。我鼓励你自己做,但如果你需要快速解决方案,它应该像下面的片段:

function find(id, children) {
  for (let child of children) {
    if (child.id === id) {
      return [child.id];
    } else if (child.childs && child.childs.length) {
      const a = this.find(id, child.childs);
      if (a.length) {
        return [...a, child.id];
      }
    }
  }

  return [];
}

const categories = [
  {
    "value": "One",
    "id": 1,
    "childs": [
      {
        "value": "Two",
        "id": 2,
        "childs": [
          {
            "value": "Three",
            "id": 3
          },
          {
            "value": "Four",
            "id": 4
          }
        ]
      },
      {
        "value": "Five",
        "id": 5
      },
      {
        "value": "Six",
        "id": 6,
        "childs": [
          {
            "value": "Seven",
            "id": 7
          },
          {
            "value": "Eight",
            "id": 8
          }
        ]
      }
    ]
  },
  {
    "value": "Nine",
    "id": 9
  }
];

console.log(find(8, categories));