Javascript显示包含匹配字符串

时间:2017-04-29 17:43:22

标签: javascript arrays javascript-objects

我非常感谢帮助解决我真正在努力解决的问题。它是什么,我有许多JavaScript对象,其中包含各种数据位,如下所示: -

Object {id: 1, shopcounty: "cornwall", shopaddress: "the cycle centre,<br />1 new street,<br />penzance,<br />tr18 2lz<br />}
Object {id: 2, shopcounty: "cornwall", shopaddress: "heliport link road,<br />long rock,<br />bude,<br />tr18 3rg"}
Object {id: 3, shopcounty: "cornwall", shopaddress: "heliport link road,<br />long rock,<br />bude,<br />tr18 3rg"}
Object {id: 4, shopcounty: "cornwall", shopaddress: "west end cottage,<br />trescowe,<br />penzance,<br />tr20 9rn"}
Object {id: 5, shopcounty: "cornwall", shopaddress: "22 joannies watch,<br />saint ives,<br />tr26 2fr"} 

我想要做的是获取用户输入值并在对象地址中搜索匹配的字符串,如果任何对象包含该字符串,则返回所有详细信息。

因此,如果用户输入&#34; bude&#34;因为他们的位置对象2和3将与他们的数据一起返回。我有下面的代码,我假设它等于真,所以它会显示每个对象。尝试了很多其他的事情,比如使用match()和indexOf()方法,但每个对象都被返回。

<input id="submit" type="submit" name="form-submit">
// user input:  "bude, united kindgom"

<script>

    $('#submit').on('click tap', function(e){
        e.preventDefault();

        var userInput   = document.getElementById('user-location').value;

        for (var i = 0; i < bikeshops.length; i++) {    
            console.log(bikeshops[i]);

            if($.inArray(userInput, bikeshops[i])){

                // console.log(bikeshops[i].shopaddress);
                // returns everything!
            }           
        }           
    });
</script>

3 个答案:

答案 0 :(得分:3)

使用Array.prototype.filterString.prototype.indexOf之类的:

$('#submit').on('click tap', function(e){
    e.preventDefault();

    var userInput   = document.getElementById('user-location').value;

    var result = bikeshops.filter(function(o) {           // for each object o in the array bikeshops
        return o.shopaddress.indexOf(userInput) !== -1;   // filter out only those who have their shopaddress property containing userInput
    });       

    console.log(result); // result will contain only the objects whose shopaddress property contain userInput
});

答案 1 :(得分:1)

这是一个有效的解决方案:

&#13;
&#13;
$('#submit').on('click tap', function (e) {
  e.preventDefault();

  var userInput = $('#user-location').val();
  
  var bikeshops = [
    {id: 1, shopcounty: "cornwall", shopaddress: "the cycle centre,<br />1 new street,<br />penzance,<br />tr18 2lz<br />"},
    {id: 2, shopcounty: "cornwall", shopaddress: "heliport link road,<br />long rock,<br />bude,<br />tr18 3rg"},
    {id: 3, shopcounty: "cornwall", shopaddress: "heliport link road,<br />long rock,<br />bude,<br />tr18 3rg"},
    {id: 4, shopcounty: "cornwall", shopaddress: "west end cottage,<br />trescowe,<br />penzance,<br />tr20 9rn"},
    {id: 5, shopcounty: "cornwall", shopaddress: "22 joannies watch,<br />saint ives,<br />tr26 2fr"}
   ];

  for (var i = 0; i < bikeshops.length; i++) {    
    if (bikeshops[i].shopaddress.indexOf(userInput) !== -1) {
      console.log(bikeshops[i].shopcounty.toUpperCase() + " - " + bikeshops[i].shopaddress);
    }           
  }           
});
&#13;
<input id="user-location" placeholder="Location...">
<input id="submit" type="submit" name="form-submit">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

$('#submit').on('click tap', function(e){
    e.preventDefault();

    let userInput   = document.getElementById('user-location').value;
    //returns array of filtered bikeshops by userInput
    let filteredArray = search(userInput, bikeshops); 

    //Attributes of array we want to print
    let attrs = ['shopcounty','shopaddress'];

    //Generate Html with results, you can change it to <p> 
    generateHtml(filteredArray, attrs, '#myList', 'li', 'ul');


});



function search(term, array){    
  return filtered = array.filter((value)=>{
    return value.includes(term.trim());
  });  
}

function generateHtml(array, attrs, id,tag, openingTag=''){
  let html = openingTag;
  array.forEach((elem)=>{
     let element = `<${tag}>`;
     attrs.forEach((attr)=>{
       element+=` ${elem[attr]}`;
     });
     element+=`</${tag}>`;
     html+=element;
  });
 if(openingTag!='') html+=`</${openingTag}>`; 
 $(id).html(html);
}