我正在尝试创建一个搜索栏来过滤嵌套JSON中的TITLES。
下面是我的JSON结构的一个小示例。
listOfArticles = {
"HOME": {
"0": {
"title": "Wall Street CEOs try to come up with new plan for First Republic",
"link": "www.ft.com/content/b67d2ab3-03bc-49fd-ac60-887373a64137"},
"1": {
"title": "Markets Briefing",
"link": "www.ft.com/content/d1d3acd2-af70-4348-b617-406ce11ca259"},
"2": {
"title": "Bid deadline for failed Silicon Valley Bank is extended as buyers hold back",
"link": "www.ft.com/content/2cbd90b6-dbca-4589-a8db-7195940fba8e"}
}
WORLD": {
"0": {
"title": "Xi praises Putin\u2019s \u2018strong leadership\u2019 in Kremlin talks",
"link": "www.ft.com/content/c82f1a91-8b60-40b6-81d9-494cf7ec2325"},
"1": {
"title": "IMF approves $3bn bailout for Sri Lanka ",
"link": "www.ft.com/content/96b9bee1-401c-418e-b92a-3e7cfb6d59a6"},
"2": {
"title": "VW\u2019s plans to pull out of Russia
"link": "www.ft.com/content/7ecb9822-d6d0-4186-9dad-4943fbde31a4"}
}
"UK" : {
"0": {
"title": "London police force should be overhauled or broken up, says review",
"link": "www.ft.com/content/a9467416-a7ea-4611-9554-b69d50aafd4d"}
"1": {
"title": "Labour calls for review of impact of financial sector uncertainty on UK ",
"link": "www.ft.com/content/6a48d3d2-20a8-4059-98fd-1965196051fd"},
"2": {
"title": "Sturgeon admits SNP leadership election has been \u2018difficult\u2019",
"link": "www.ft.com/content/9658b054-6483-499f-94b9-94eb2f992660"}
}
这是我的代码
import { useEffect, useState } from 'react';
const [searchWord, setSearchWord] = useState("")
const filteredArticles = Object.keys(listOfArticles).map(page => {
return (
Object.keys(listOfArticles[page]).filter(function(item){
console.log(listOfArticles[page][item].title) //This log works as expected
return (
<div>
{listOfArticles[page][item].title.toLowerCase().includes(searchWord.toLowerCase())}
</div>
)
})
)
})
console.log(filteredArticles)
return (
<div>
<input type='text' placeholder='Search...' onChange={ (userInput) => {
setSearchWord(userInput.target.value)
}}/>
{filteredArticles}
</div>
);
}
我也试过用Object.entries()
替换Object.keys()
,但不确定是否正确使用。
我已经删除了底部返回中的大量代码,这些代码可以毫无问题地循环通过未过滤的JSON。
我想做的事:目前filteredArticles
返回一个数组,但它甚至与我想要的不太接近。我希望它返回一个JSON,格式完全相同,并删除不在搜索词中的对象。对象即{"0": {"title": ###, "link": ###}}
filteredArticles Output ->
非常感谢。
1条答案
按热度按时间vhmi4jdf1#
我建议你把对象改为数组,就好像你总是有“0”,“1”等作为键一样,这并不是真的必要的。数组也有更强的顺序保证。
在你的情况下,确保你理解filter和map函数是很重要的。如果你从filter返回一些东西,它将被包含在最终的渲染中,因为你总是返回它是没有用的。
您需要将其拆分为两个步骤,首先过滤所有您想要的行,然后显示它们。