包含使用lodash.js的搜索

时间:2017-03-29 05:26:27

标签: javascript search underscore.js contains

var codes = [
{id: 1, code: '123'},
{id: 2, code: '14123'},
{id: 3, code: '556'},
{id: 4, code: '71239'},
{id: 5, code: '289'},
];

var filterCodes = _.filter(codes, function (o) {
  return o.code ? _.includes(o.code, '123') : false
});

输出将是:'123','14123','71239'

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你就是在寻找所有代码而不是整个对象,其中包含“123”。

array.forEach

var codes = [{id: 1, code: '123'},{id: 2, code: '14123'},{id: 3, code: '556'},{id: 4, code: '71239'},{id: 5, code: '289'}];

var result = [];
codes.forEach(function(o){
  o.code && o.code.indexOf('123') >= 0 && result.push(o.code)
});
console.log(result)

答案 1 :(得分:0)

为什么甚至为Lodash打扰呢?此外,我认为您错过了地图步骤......



const codes = [{"id":1,"code":"123"},{"id":2,"code":"14123"},{"id":3,"code":"556"},{"id":4,"code":"71239"},{"id":5,"code":"289"}]

const filterCodes = codes
  .filter(o => typeof o.code === 'string' && o.code.includes('123'))
  .map(o => o.code)
console.info(filterCodes)