如何找到与提供的子弹匹配的某些对象的索引

时间:2018-09-28 01:17:43

标签: javascript data-structures

我有以下数据结构。这是一个深层嵌套的对象。

从下面的数据结构中,我需要找到一个标有level-1.1.3的对象的索引,这样我才能知道是否为我提供了该标头,我必须在该对象子数组中添加项。如果找不到任何子弹,则在顶层添加Another Level 1 B对象。

我尝试了以下方法,但是我没有采用有效的方法,也找不到索引,但是找到了整个对象。问题是,它也会进入else块,因此,如果我返回null或else块中的某物,那么如果对象太深,将无法找到对象中包含的子弹。

const data = [{
    title: "Level 1 A",
    slug: "level-1-A",
    url: "url",
    children: [{
      expanded: true,
      title: "Level 1.1",
      slug: "level-1.1",
    }]
  },
  {
    title: "Another Level 1 B",
    slug: "another-level-1-b",
    url: "url",
    children: []
  },
  {
    title: "Level 1 C",
    slug: "level-1-c",
    expanded: true,
    children: [{
      expanded: true,
      title: "Level 1.1",
      slug: "level-1.1",
      children: [{
        title: "Level 1.1.1",
        slug: "level-1.1.1",
        url: "/child",
        children: [{
          title: "Level 1.1.2",
          slug: "level-1.1.2",
          url: "/",
          children: [{
            title: "Level 1.1.3",
            slug: "level-1.1.3",
            url: "/"
          }]
        }]
      }]
    }]
  }
];


function findIndex(data, slug) {
  var index = 0;
  for (var i = 0; i < data.length; i++) {
    if (data[i].slug === slug) {
      console.log('found in depth', data[i]);
      break;
    } else if (data[i].children && data[i].children.length > 0) {
      console.log('did not find in first level')
      findIndex(data[i].children, slug)
    } else {
      console.log('did not find at all')
    }
  }
}


findIndex(data, slug = "level-1.1.3")

1 个答案:

答案 0 :(得分:1)

您可以在其中使用数组查找和递归查找块(或其他任何东西):

var data = [
  {
    title: "Level 1 A",
    slug: "level-1-A",
    url: "url",
    children: [
      {
        expanded: true,
        title: "Level 1.1",
        slug: "level-1.1",
      }
    ]
  },
  {
    title: "Another Level 1 B",
    slug: "another-level-1-b",
    url: "url",
    children: []
  },
  {
    title: "Level 1 C",
    slug: "level-1-c",
    expanded: true,
    children: [
      {
        expanded: true,
        title: "Level 1.1",
        slug: "level-1.1",
        children: [
          {
            title: "Level 1.1.1",
            slug: "level-1.1.1",
            url: "/child",
            children: [
              {
                title: "Level 1.1.2",
                slug: "level-1.1.2",
                url: "/",
                children: [
                  { title: "Level 1.1.3", slug: "level-1.1.3", url: "/" }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
];

function findslug(title){
  var slug = "";
  data.find(function f(current){
    if(current.title === title){
      slug = current.slug;
      return current;
    };
    if(current.children)
      return current.children.find(f);
  });
  return slug;
}

console.log(findslug("Level 1.1.3"));
console.log(findslug("Level 1 C"));