JavaScript查找一个数组中符合某个条件的值,并将符合条件的值存入新的数组

1. 利用find函数和es6箭头函数,下面方法取到数组中满足条件的第一个元素;

var newArray  = {};//新对象
var array = [
 {name:'aiai',age:18},
 {name:'sisi',age:18},
 {name:'lulu',age:18},
 {name:'sisi',age:19}
]; 
//查找符合条件值并存入新数组
newArrar = this.array.find((item) => {
   if(item.name === 'sisi'){
     return item
   }
 })
//此时 newArray = {name:'sisi',age:18}

2. 查找符合条件的所有元素

var newArray  = [];//新数组
var j = 0;
var array = [
 {name:'aiai',age:18},
 {name:'sisi',age:18},
 {name:'lulu',age:18},
 {name:'sisi',age:19}
]; //目标数组
 
//查找符合条件值并存入新数组
for(let i in array){
 if(array[i].name == 'sisi'){
  newArray[j++] = array[i]
 }
}
//此时 newArray = [{name:'sisi',age:18},{name:'sisi',age:19}]

JS 数组模糊搜索

var da={pageDesc:{rowEnd:12, totalRows:11}, objList:
            [{rsincd:1, rsnm :'玛瑙河水库',pname:'江苏',prsc:'大',rsdr:"s1",maxdmhg:131,lat:'',lng:''},
                {rsincd:2, rsnm :'湄公河水闸',pname:'云南',prsc:'大',rsdr:"s2",maxdmhg:54,lat:'',lng:''},
                {rsincd:3, rsnm :'金沙江泵站',pname:'江西',prsc:'中',rsdr:"s3",maxdmhg:23,lat:'',lng:''},
                {rsincd:4, rsnm :'怒江水库',pname:'贵州',prsc:'大',rsdr:"s4",maxdmhg:51,lat:'',lng:''},
                {rsincd:5, rsnm :'鸭绿江水电站',pname:'黑龙江',prsc:'小',rsdr:"s5",maxdmhg:101,lat:'',lng:''},
                {rsincd:6, rsnm :'长江水闸',pname:'四川',prsc:'中',rsdr:"s6",maxdmhg:85,lat:'',lng:''},
                {rsincd:7, rsnm :'黄河水库',pname:'河南',prsc:'大',rsdr:"s7",maxdmhg:13,lat:'',lng:''},
                {rsincd:8, rsnm :'北戴河水电站',pname:'河北',prsc:'小',rsdr:"s8",maxdmhg:15,lat:'',lng:''},
                {rsincd:9, rsnm :'雅鲁藏布江水库',pname:'西藏',prsc:'大',rsdr:"s9",maxdmhg:54,lat:'',lng:''},
                {rsincd:10, rsnm :'泉河堤防',pname:'山西',prsc:'中',rsdr:"s10",maxdmhg:33,lat:'',lng:''},
                {rsincd:11, rsnm :'珠江水库',pname:'广州',prsc:'小',rsdr:"s11",maxdmhg:2,lat:'',lng:''}]
    };
 //JS 数组模糊搜索
    function searchList(str, container,filed) {
        var newArrar = [];
        var arry=[];
        //将所有元素+1
        newArrar = container.map(function(item,index,container){
            if(filed=="rsnm"){
                if(item.rsnm.indexOf(str) != -1){
                    return item;
                }
            }else if(filed=="pname"){
                if(item.pname.indexOf(str) != -1){
                    return item;
                }
            }
        });
//去除为underfined的元素
        newArrar.forEach(function (item,index) {
            if(item!=undefined){
                arry.push(item);
            }
        });
        return arry;
    }

你可能感兴趣的:(前端,js,web,app)