从obj数据在普通JS中自动完成

时间:2018-06-27 18:45:08

标签: javascript autocomplete

我正在尝试在普通javascript中创建“自动完成”搜索输入字段(无jquery或jquery-ui)。我想从我的javascript对象数据中提取“自动完成”作为“建议”。我正在尝试以下内容;无济于事(没有错误,只有响应输出)。功能应该是“匹配”范围的缩小;即,我将首先建议您开始输入s的结果,等等。

HTML。

<div class="row">
    <input type="text" id="autoSuggest" placeholder="Search..." onkeyup="changeInput(this.value)">
    <div id="result"></div>
</div>

此功能的JavaScript尝试:

function matchIt(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return json.filter(function(file) {
    if (file.match(reg)) {
      return file;
    }
  });
}

function changeInput(val) {
  var autoCompleteResult = matchIt(val);
  document.getElementById("result").innerHTML = autoCompleteResult;
}

JS obj数据:

var json =[{
            "Name": "zips",
            "Type": "Directory",
            "DateModified": "6/14/2018 17:22:50",
            "Size": "5 KB",
        }, {
            "Name": "presets",
            "Type": "Directory",
            "DateModified": "5/11/2018 7:32:10",
            "Size": "2 KB",
        }, {
            "Name": "workflow",
            "Type": "Directory",
            "DateModified": "6/26/2018 10:29:59",
            "Size": "6 KB",
        },{
            "Name": "software",
            "Type": "Directory",
            "DateModified": "3/16/2018 10:29:59",
            "Size": "16 KB",
        },{
            "Name": "mmm_data",
            "Type": "Directory",
            "DateModified": "6/27/2018 1:19:29",
            "Size": "3 KB",
        },{
            "Name": "jobs",
            "Type": "Directory",
            "DateModified": "4/27/2018 11:59:59",
            "Size": "3 KB",
        },
];

1 个答案:

答案 0 :(得分:2)

您需要匹配file.Name,而不是file。然后,过滤器回调函数应返回true/false值,而不是对象

var json = [{
  "Name": "zips",
  "Type": "Directory",
  "DateModified": "6/14/2018 17:22:50",
  "Size": "5 KB",
}, {
  "Name": "presets",
  "Type": "Directory",
  "DateModified": "5/11/2018 7:32:10",
  "Size": "2 KB",
}, {
  "Name": "workflow",
  "Type": "Directory",
  "DateModified": "6/26/2018 10:29:59",
  "Size": "6 KB",
}, {
  "Name": "software",
  "Type": "Directory",
  "DateModified": "3/16/2018 10:29:59",
  "Size": "16 KB",
}, {
  "Name": "mmm_data",
  "Type": "Directory",
  "DateModified": "6/27/2018 1:19:29",
  "Size": "3 KB",
}, {
  "Name": "jobs",
  "Type": "Directory",
  "DateModified": "4/27/2018 11:59:59",
  "Size": "3 KB",
}, ];




function matchIt(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return json.filter(file => !!file.Name.match(reg));
}

function changeInput(val) {
  if (val.length == 0) return;
  var autoCompleteResult = matchIt(val);
  document.getElementById("result").innerHTML = autoCompleteResult.map(i => i.Name).join('<br>')
}
<div class="row">
  <input type="text" id="autoSuggest" placeholder="Search..." onkeyup="changeInput(this.value)">
  <div id="result"></div>
</div>