仅显示包含特定字符串的数组中的对象

时间:2016-10-11 13:02:28

标签: javascript html arrays object

我试图创建一个可以键入字符串的东西,而js只显示包含该字符串的对象。例如,我键入Address1并搜索每个地址的值然后显示它(这里:它将是Name1)。这是我的代码https://jsfiddle.net/76e40vqg/11/

HTML

<input>
<div id="output"></div>

JS

var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];

var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){    
        restoName.push(data[i].name);
        restoAddress.push(data[i].address);
        restoRate.push(data[i].rate);
        restoImage.push(data[i].image);
}

for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
  }

我真的尝试了很多东西,但没有任何工作,这就是我在这里问的原因......

2 个答案:

答案 0 :(得分:2)

不要将详细信息存储为单独的数组。而是使用类似于返回的数据对象的结构。

for(i = 0; i < data.length; i++){ 
    if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
        document.getElementById("output").innerHTML += data[i].name;
    }
}

编辑JSFiddle:https://jsfiddle.net/76e40vqg/17/

干杯!

答案 1 :(得分:1)

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

&#13;
&#13;
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');


function search(event) {
  var value = event.target.value;
  
  output.innerHTML = '';
  
  data.forEach(function(item) {
    var found = false;
    Object.keys(item).forEach(function(val) {
      if(item[val].indexOf(value) > -1) found = true;
    });
    
    if(found) {
      // ouput your data
      var div = document.createElement('div');
      div.innerHTML = item.name
      output.appendChild(div);
    }
  });
  
  return true;
}
&#13;
<input type="search" id="search" />

<div id="output"></div>
&#13;
&#13;
&#13;