简体   繁体   English

来自2个不同数据源的JS模式匹配

[英]JS Pattern matching from 2 different sources of data

I have 2 tables (which can increase in future) with rows like 我有2个表格(将来可能会增加),其中包含以下行

 <table> <tr> <th>name</th> <th>salary</th> </tr> <tr> <td>a</td> <td>12</td> </tr> <tr> <td>bb</td> <td>24</td> </tr> <tr> <td>aab</td> <td>26</td> </tr> <tr> <td>aabb</td> <td>28</td> </tr> </table> 

and

 <table> <tr> <th>name</th> <th>salary</th> </tr> <tr> <td>ac</td> <td>22</td> </tr> <tr> <td>dc</td> <td>34</td> </tr> <tr> <td>acdc</td> <td>36</td> </tr> <tr> <td>cdcc</td> <td>38</td> </tr> </table> 

I think this can be done with JSON (with key being name and salary being value) but how can i achieve this is an issue. 我认为可以使用JSON(键为名称,薪金为值)来完成此操作,但是如何实现这一点却是一个问题。

I will put a value in the searchbox. 我将在搜索框中输入一个值。 I expect my program/script to show the salary according to the longest posible value entered with data fetched from both tables. 我希望我的程序/脚本根据从两个表中获取的数据中输入的最长可能值来显示薪水。 For eg when in enter just a,it should show 12 but when i enter ac, it should show 22 and acdc=36 and so on. 例如,当输入a时,它应该显示12,但是当我输入ac时,它应该显示22,acdc = 36,依此类推。 Any example in JS/React/Angular is welcome. 欢迎使用JS / React / Angular中的任何示例。

You should add HTML: 您应该添加HTML:

<input id="nameInput">

In clear js I'd write it like this: 在清晰的js中,我会这样写:

const arr1 = [{ name: 'a', salary: 12 }, { name: 'bb', 'salary': 24 }];
const arr2 = [{ name: 'ac', salary: 22 }, { name: 'dc', 'salary': 34 }];

document.getElementById("nameInput").addEventListener(function() {
  // depending on what you want, you can change condition or function
  const foundValue = [ ...arr1, ...arr2].find(el => {
    return el === this.value;
  });

  // here you can do whatever you want with found value
}

Assuming we are fetching data from two tables and having stored in two arrays. 假设我们从两个表中获取数据并存储在两个数组中。

let table1Data = [ {name: 'a', salary: 50}, {name: 'bc', salary: 45} ];
let table2Data = [ {name: 'ac', salary: 100}, {name: 'db', salary: 20} ];

// click event on search button
document.getElementById('search-btn').addEventListener('click', () => {
    let searchInput = document.getElementById('search-input').value;

    // filtered data which has matching
    let matchedData = [...table1Data, ...table2Data]
                        .filter(record => record.name === searchInput);
    /* 
       we can chain map function to the above statement
       for further extraction of only salary key from the filtered objects
    */
}

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

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