简体   繁体   English

如何根据用户输入和 map 过滤对象对应的数组?

[英]How to filter the objects based on user input and map their corresponded array?

This is bugging me quite a bit.这让我很烦。 I hope someone can help me with it.我希望有人可以帮助我。 I'm doing this in React.我在 React 中这样做。

Here is the data (objects that have an array inside):这是数据(内部有数组的对象):

{
   "Susan": {
      "likes": [
         "shopping",
         "skiing",
         "surfing"
      ],
      "hates": [
         "cycling",
         "reading",
         "cleaning"
      ]
   },
   "Andrew": {
      "likes": [
         "driving",
         "hiking",
         "coding"
      ],
      "hates": [
         "dancing",
         "running",
         "cleaning dishes"
      ]
   }
}

Now, in this case, I would like to display/map both arrays ("likes" and "hates") based on user choosing "Susan" or "Andrew".现在,在这种情况下,我想根据用户选择“Susan”或“Andrew”来显示/映射 arrays(“喜欢”和“讨厌”)。 I just can't seem to logical connect this.我似乎无法在逻辑上将其联系起来。

Let's say user input is a variable:假设用户输入是一个变量:

let input = "Susan"

I have something like:我有类似的东西:

Object.values(data).filter((val) => {
   if(input === val) {
      return val;
   }
}).map((obj) => {
   return ( 
      <div>
         <p> {obj.likes} </p>
         <p> {obj.hates} </p>
      </div>
);
})

I know there has to be some kind of binding with the keys, but I don't know how to do that.我知道必须与键进行某种绑定,但我不知道该怎么做。

Your help is very much appreciated!非常感激你的帮助!

I think you may be overcomplicating this if I'm not misunderstanding the question.如果我没有误解这个问题,我认为你可能过于复杂了。 data['Susan'] will get you an entry with the 'likes' and 'hates' arrays. data['Susan']将为您提供一个带有“喜欢”和“讨厌”arrays 的条目。 You can use it like this:你可以像这样使用它:

const data = {
    "Susan": {
       "likes": [
          "shopping",
          "skiing",
          "surfing"
       ],
       "hates": [
          "cycling",
          "reading",
          "cleaning"
       ]
    },
    "Andrew": {
       "likes": [
          "driving",
          "hiking",
          "coding"
       ],
       "hates": [
          "dancing",
          "running",
          "cleaning dishes"
       ]
    }
}
     
const createDiv = (name) => {
    let entry = data[name];
    return ( 
        <div>
            <p> {entry.likes} </p>
            <p> {entry.hates} </p>
        </div>
    );
}

let element = createDiv('Susan');

You should filter your data as entries ie Object.entries so that you retain the object key (name) and the value (likes and dislikes).您应该将数据过滤为条目,即Object.entries ,以便保留 object 键(名称)和值(喜欢和不喜欢)。

I added a debounce to the input field so that entries only get filtered/rendered when the user stops typing.我在输入字段中添加了去抖动功能,以便只有在用户停止输入时才会过滤/呈现条目。

 const filteredResults = document.querySelector('#filtered-results'), searchTerm = document.querySelector('#search-term'); const render = () => { const filtered = searchTerm.value.trim().length? Object.entries(data).filter(([key, value]) => searchTerm.value.includes(key)): Object.entries(data); filteredResults.innerHTML = ` <ul class="entries"> ${filtered.map(([key, { likes, hates }]) => { return ` <li> <h1>${key}</h1> <h2>Likes</h2> <ul class="sublist"> ${likes.map(like => `<li>${like}</li>`).join('')} </ul> <h2>Hates</h2> <ul class="sublist"> ${hates.map(hate => `<li>${hate}</li>`).join('')} </ul> </li> `; }).join('')} </ul> `; }; const main = () => { render(); searchTerm.addEventListener('keyup', handleKeyUp); }; const debounce = (callback, wait) => { let timeoutId = null; return (...args) => { window.clearTimeout(timeoutId); timeoutId = window.setTimeout(() => { callback.apply(null, args); }, wait); }; }; const handleKeyUp = debounce((event) => { render(); }, 500); const data = { "Susan": { "likes": [ "shopping", "skiing", "surfing" ], "hates": [ "cycling", "reading", "cleaning" ] }, "Andrew": { "likes": [ "driving", "hiking", "coding" ], "hates": [ "dancing", "running", "cleaning dishes" ] } }; main();
 *, *:before, *:after { box-sizing: border-box; } html, body { width: 100%; height: 100%; margin: 0; padding: 0; } h1, h2 { margin: 0; padding: 0; font-weight: normal; } body { display: flex; flex-direction: column; align-items: center; padding: 1rem; }.entries { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: 0; padding: 0; list-style-type: none; gap: 1rem; padding: 0.5rem; }.entries > li { display: flex; flex-direction: column; min-width: 20rem; background: #EEE; border: thin solid #AAA; padding: 0.5rem; }.entries li h1 { font-weight: bold; font-size: 1.25rem; margin: 0.25rem 0 0.5rem 0; }.entries li h2 { font-weight: bold; font-size: 1rem; margin: 0.125rem 0 0.25rem 0; }.sublist { margin: 0; padding: 0; list-style-type: none; }.sublist > li { display: inline-block; margin-right: 0.5rem; padding: 0.25rem; border: thin solid #AAA; }
 <input type="text" id="search-term" placeholder="Filter by name" /> <hr /> <div id="filtered-results"></div>

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

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