json数组用js查询

下面有个json数组:

const products=[
    {"name": "red01","url": "https://example.com/JXIS14AHZ9MX3"},
    {"name": "green01","url": "https://example.com/JXISM5MAE9IXY"},
    {"name": "yellow01","url": "https://example.com/JXISO1ZS24JIT"},
    {"name": "blue01","url": "https://example.com/JXISO3DMUPLSW"},
    {"name": "red02","url": "https://example.com/JXISO7VRRZR56"},
    {"name": "red03","url": "https://example.com/JXISOAB64OBOE"},
    {"name": "green02","url": "https://example.com/JXISORRSSQGPS"},
    {"name": "yellow02","url": "https://example.com/JXISOWOCC3IZP"},
    {"name": "blue02","url": "https://example.com/JXISPBQSYV1MQ"},
    {"name": "red04","url": "https://example.com/JXISPQ5DJ4HKR"}
];

我想用颜色作为关键词(也就是red、green、blue、yellow)查询该数组的name字段,结果返回包含该关键词的记录(返回格式仍然是原格式json数组)。

问题:
用js实现,应该怎么做呢?

阅读 2.2k
2 个回答
    function filterByKey (arr, key) {
        return  arr.filter(item => item.name.indexOf(key) >= 0)
    }
    filterByKey(products, 'red')
    /* 结果
        [
        {name: "red01", url: "https://example.com/JXIS14AHZ9MX3"},
        {name: "red02", url: "https://example.com/JXISO7VRRZR56"},
        {name: "red03", url: "https://example.com/JXISOAB64OBOE"},
        {name: "red04", url: "https://example.com/JXISPQ5DJ4HKR"}
       ]
    */

参考文章

可以参考我里面写的,将json转换成js中的对象,再通过键值比对拿到相应的记录

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题