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

huangapple go评论70阅读模式
英文:

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)
  })
})

但不确定如何做

[这是示例链接][1]

有什么想法吗

  [1]: https://jsfiddle.net/tox4dqj6/

如果您需要进一步的解释或代码示例,请随时告诉我。

英文:

I have an array of objects as follows:

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: [],
}
]

And I have an array of search terms as follows:

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

I want to search through the data array, and find all objects which have one of those searched terms.

The result should be as follows:

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

I'm not sure how to do that, because the properties of the nested arrays are not the same.

It needs to be something as follows:

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

But not sure how to do that.

Here is the fiddle.

Any idea?

答案1

得分: 2

以下是代码的翻译部分:

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

const data = [
  {"slug": "home", "content_one": [], "content_two": [{"title": "一些标题", "description": "一些描述"}], "content_three": [{"main_title": "一些标题", "content": "这里是一些内容"}]},
  {"slug": "contact", "content_one": [{"title": "一些标题", "description": "一些描述"}], "content_two": [], "content_three": []},
  {"slug": "about-us", "content_one": [], "content_two": [], "content_three": []}
];

const search_terms = ['一些', '标题'];

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);

希望这有所帮助!如果您需要进一步的翻译或解释,请告诉我。

英文:

You could first find all objects with matching text using recursion and then do the count and remove duplicates.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = [{&quot;slug&quot;:&quot;home&quot;,&quot;content_one&quot;:[],&quot;content_two&quot;:[{&quot;title&quot;:&quot;Some title&quot;,&quot;description&quot;:&quot;Some description&quot;}],&quot;content_three&quot;:[{&quot;main_title&quot;:&quot;Some title&quot;,&quot;content&quot;:&quot;Here comes some content&quot;}]},{&quot;slug&quot;:&quot;contact&quot;,&quot;content_one&quot;:[{&quot;title&quot;:&quot;Some title&quot;,&quot;description&quot;:&quot;Some description&quot;}],&quot;content_two&quot;:[],&quot;content_three&quot;:[]},{&quot;slug&quot;:&quot;about-us&quot;,&quot;content_one&quot;:[],&quot;content_two&quot;:[],&quot;content_three&quot;:[]}]
const search_terms = [&#39;Some&#39;, &#39;title&#39;]
function search(data, terms, slug = &#39;&#39;) {
const result = [];
if (data.slug) {
slug = data.slug;
}
if (Array.isArray(data)) {
data.forEach(e =&gt; result.push(...search(e, terms, slug)))
} else {
let added = false;
for (let i in data) {
if (typeof data[i] == &#39;object&#39;) {
result.push(...search(data[i], terms, slug));
} else {
const check = terms.some(t =&gt; data[i].toLowerCase().includes(t.toLowerCase()));
if (check &amp;&amp; !added) {
result.push({
slug,
text: data[i]
});
added = true;
}
}
}
}
return result;
}
function uniq(data) {
return data.reduce((r, e) =&gt; {
const match = r.find(({ count, ...rest }) =&gt; _.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)

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月6日 17:30:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定