根据用户输入过滤对象数组值

时间:2018-03-16 14:32:10

标签: javascript

我想根据用户输入过滤对象数组值。

这是jsfiddle

// Copied from https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js
const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;
if (!Object.values) {
  Object.values = function values(O) {
    return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []);
  };
}

// Copied code ends here;

let data = {
  Belgien: [{
    code: "BRU",
    name: "Bryssel",
    aliases: "Bryssel,BRU,Belgien"
  }],
  Cypern: [{
      code: "LCA",
      name: "Larnaca",
      aliases: "Larnaca,LCA,Cypern,Ayia Napa,Protaras,Fig Tree Bay,Larnaca"
    },
    {
      code: "PFO",
      name: "Paphos",
      aliases: "Paphos,PFO,Cypern"
    }
  ]
}

let userInput = "lar";

let filteredData = Object.values(data).map(values => values.filter(value =>
  value.name.toLowerCase().indexOf(userInput) !== -1));

console.log(filteredData);

问题在于我正确地过滤了值,但是我没有得到与这些值相关联的键,在本例中是国家。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您可以使用功能filter并使用indexOfObject.keys功能过滤数据。

此替代方法使用函数let data = { Belgien: [{ code: "BRU", name: "Bryssel", aliases: "Bryssel,BRU,Belgien" }], Cypern: [{ code: "LCA", name: "Larnaca", aliases: "Larnaca,LCA,Cypern,Ayia Napa,Protaras,Fig Tree Bay,Larnaca" }, { code: "PFO", name: "Paphos", aliases: "Paphos,PFO,Cypern" } ]}, userInput = "lar", filteredData = Object.keys(data).reduce((a, k) => { a[k] = data[k].filter(({name}) => name.toLowerCase().indexOf(userInput) > -1); return a; }, {}); console.log(filteredData);来恢复所需的密钥。



.as-console-wrapper { max-height: 100% !important; top: 0; }

{{1}}




答案 1 :(得分:1)

您可以迭代键并返回仅包含过滤数据的对象。



var data = { Belgien: [{ code: "BRU", name: "Bryssel", aliases: "Bryssel,BRU,Belgien" }], Cypern: [{ code: "LCA", name: "Larnaca", aliases: "Larnaca,LCA,Cypern,Ayia Napa,Protaras,Fig Tree Bay,Larnaca" }, { code: "PFO", name: "Paphos", aliases: "Paphos,PFO,Cypern" }] },
    userInput = "lar",
    filteredData = Object.keys(data).reduce((r, k) => {
        var temp = data[k].filter(({ name }) => name.toLowerCase().includes(userInput));
        if (temp.length) {
            r[k] = temp;
        }
        return r;
    }, {});

console.log(filteredData);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:1)

您可以使用Object.entries这样完成工作:

let filteredData = Object.entries(data).reduce((acc, values) => {
  const value = values[1].filter(value =>
      value.name.toLowerCase().indexOf(userInput) !== -1),
    key = values[0];
  acc[key] = value;
  return acc;
}, {});