js对象,怎么根据两个参数去匹配对应的数据

CaixK
  • 511

怎么根据两个字段去匹配,比如,val1 = '黄色' val2 = '23' 就匹配list里第一条

list:[
    {
        id:1,
        skuName: "{"颜色":"黄色","尺码":"23"}",
        name:'裤子',
        img:'/2020/01/11/1609929447463906.png'
    },
    {
        id:2,
        skuName: "{"颜色":"黄色","尺码":"24"}",
        name:'裤子',
        img:'/2020/01/11/1609929447463765.png'
    },
    {
        id:3,
        skuName: "{"颜色":"蓝色","尺码":"23"}",
        name:'裤子',
        img:'/2020/01/11/1609929447490906.png'
    },
    {
        id:4,
        skuName: "{"颜色":"蓝色","尺码":"24"}",
        name:'裤子',
        img:'/2020/01/11/1609929447465496.png'
    }
]
回复
阅读 1.6k
5 个回答

list.find(fun)

fun 就是判断是否合规的方法,入参是当前对象 list[0] list[1]

image.png
![上传中...]()

UxieKong
  • 683

根据linong老师的思路写如下代码

let list = [
  {
    id: 1,
    skuName: { 颜色: "黄色", 尺码: "23" },
    name: "裤子",
    img: "/2020/01/11/1609929447463906.png",
  },
  {
    id: 2,
    skuName: { 颜色: "黄色", 尺码: "24" },
    name: "裤子",
    img: "/2020/01/11/1609929447463765.png",
  },
  {
    id: 3,
    skuName: { 颜色: "蓝色", 尺码: "23" },
    name: "裤子",
    img: "/2020/01/11/1609929447490906.png",
  },
  {
    id: 4,
    skuName: { 颜色: "蓝色", 尺码: "24" },
    name: "裤子",
    img: "/2020/01/11/1609929447465496.png",
  },
];

function findItem(list) {
  return (...args) => {
    return list.find(
      (item) => Object.values(item.skuName).toString() == args.toString()
    );
  };
}

console.log(findItem(list)("黄色", 23));

定义一个共用的方法来实现。设置参数为color和size。可以筛选一个条件也可以筛选两个。

// list 查询数据库返回的json
// color 查询的颜色参数
// size 查询的尺寸参数
function findObj(list, color="", size="") {
    let newArr = [];
    if(list.length > 0 ) {
        list.forEach(item => {
            if(color && item.skuName.color === color && size && item.skuName.size === size)     {
                newArr.push(item)
               }
            else if( !color && size && item.skuName.size === size) {
                newArr.push(item)
            }
            else if( !size && color && item.skuName.color === color) {
                newArr.push(item)
            } else {
                console.log("没有设置筛选条件")
            }  
        })
    }
    return newArr
}

如果数据文件结构明确,查询数据结构明确,是一个比较好处理的过程,就是遍历比较。
这里我想可能不明确的地方是查询数据结构不明确,则可以考虑同时双搜索,毕竟查询变量只有2个,交换处理一下问题也比较好解决,而且这两种数据差异很大。

function findObj(list, val1,val2 ){
    let rt={};
    for(let i=0;i<list.length;i++){
        if( (list[i]["skuName"]["颜色"]==val1 && list[i]["skuName"]["尺码"]==val2) ||
            (list[i]["skuName"]["颜色"]==val2 && list[i]["skuName"]["尺码"]==val1) )
            {
                rt=list[i];
                break;
             }
    }
    return rt;
}
console.log(findObj(list,23,"蓝色" ));
console.log(findObj(list,"黄色",23 ));
console.log(findObj(list,"黄色",25 ));

。。。。

val1 = "黄色";
val2 = "24";
const result = list.find(i => i.skuName["颜色"] === val1 && i.skuName["尺码"]=== val2);

如果结果唯一就用 list.find, 返回列表单个元素

如果结果不唯一就用list.filter, 返回多个元素

宣传栏