繁体   English   中英

如何使用 Javascript 或 Lodash 搜索嵌套对象数组

[英]How to search through array of nested objects using Javascript or Lodash

我有一个对象数组,如下所示:

const data = [
  {
    slug: "home",
    content_one: [],
    content_two: [
      {
        title: "Some title",
        description: 'Some description'
      }
    ],
    content_three: [
      {
        main_title: "Some title",
        content: 'Here comes some content'
      }
    ],
  },
  {
    slug: "contact",
    content_one: [
      {
        title: "Some title",
        description: 'Some description'
      }
    ],
    content_two: [],
    content_three: [],
  },
  {
    slug: "about-us",
    content_one: [],
    content_two: [],
    content_three: [],
  }
]

我有一系列搜索词,如下所示:

const search_terms = ['Some', 'title']

我想搜索数据数组,并找到所有具有这些搜索词之一的对象。

结果应如下所示:

const res = [
    {
    slug: 'home',
    text: 'Some title',
    count: 2
  },
  {
    slug: 'contact',
    text: 'Some title',
    count: 1
  }
]

我不知道该怎么做,因为嵌套数组的属性不一样。

它需要如下所示:

let result = []
search_terms.map(term => {
    data.filter(item => {
    console.log(item)
  })
})

但不确定如何做到这一点。

这是小提琴。

任何的想法?

您可以首先使用递归找到具有匹配文本的所有对象,然后进行计数并删除重复项。

 const data = [{"slug":"home","content_one":[],"content_two":[{"title":"Some title","description":"Some description"}],"content_three":[{"main_title":"Some title","content":"Here comes some content"}]},{"slug":"contact","content_one":[{"title":"Some title","description":"Some description"}],"content_two":[],"content_three":[]},{"slug":"about-us","content_one":[],"content_two":[],"content_three":[]}] const search_terms = ['Some', 'title'] function search(data, terms, slug = '') { const result = []; if (data.slug) { slug = data.slug; } if (Array.isArray(data)) { data.forEach(e => result.push(...search(e, terms, slug))) } else { let added = false; for (let i in data) { if (typeof data[i] == 'object') { result.push(...search(data[i], terms, slug)); } else { const check = terms.some(t => data[i].toLowerCase().includes(t.toLowerCase())); if (check && !added) { result.push({ slug, text: data[i] }); added = true; } } } } return result; } function uniq(data) { return data.reduce((r, e) => { const match = r.find(({ count, ...rest }) => _.isEqual(rest, e)); if (match) match.count++ else r.push({ ...e, count: 1 }); return r; }, []) } const array = search(data, search_terms); const result = uniq(array); console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM