Underscore.js使用嵌套数组查找和返回元素

时间:2018-12-15 12:29:54

标签: javascript jquery underscore.js

我有这样的数据结构

        var masterObj = [{
            "_id" : "2i4NGzpEpnKZhkxY8",
            "master_sku" : "UAT43-S",
            "available" : [ 
                {
                    "marketplace_name" : "xyx",
                    "doc_id" : "WCw8Hsyw4D3ab8TAZ"
                }
            ]
        }
        {
            "_id" : "2mf6hghQ7f32CrA3X",
            "master_sku" : "UAT43-XL",
            "available" : [ 
                {
                    "marketplace_name" : "abc",
                    "doc_id" : "QduDKpT2HqmuaFHRz",
                }
            ]
        }]

我正在使用underscor.js,而我的查询就是这样

  var result = _.findWhere(masterObj, { "available.doc_id": "WCw8Hsyw4D3ab8TAZ" });    

必填结果是

   {
        "_id" : "2i4NGzpEpnKZhkxY8",
        "master_sku" : "UAT43-S",
        "available" : [ 
            {
                "marketplace_name" : "xyx",
                "doc_id" : "WCw8Hsyw4D3ab8TAZ"
            }
        ]
    }

如何获得指定的输出。预先感谢。

1 个答案:

答案 0 :(得分:2)

您不需要下划线。将JavaScript的本机find数组方法与回调函数一起使用,以查找具有正确的available的元素doc_id数组。

如果您知道available仅包含一个元素:

const arr = [{"_id":"2i4NGzpEpnKZhkxY8","master_sku":"UAT43-S","available":[{"marketplace_name":"xyx","doc_id":"WCw8Hsyw4D3ab8TAZ"}]},{"_id":"2mf6hghQ7f32CrA3X","master_sku":"UAT43-XL","available":[{"marketplace_name":"abc","doc_id":"QduDKpT2HqmuaFHRz"}]}]

const result = arr.find(obj => {
  return obj.available[0].doc_id === 'WCw8Hsyw4D3ab8TAZ';
});

console.log(result);  

如果available具有多个元素,请使用some

const arr = [{"_id":"2i4NGzpEpnKZhkxY8","master_sku":"UAT43-S","available":[{"marketplace_name":"xyx","doc_id":"WCw8Hsyw4D3ab8TAZ"},{"marketplace_name":"bob","doc_id":"WCw8Hsyw4D3a8TAZ"}]},{"_id":"2mf6hghQ7f32CrA3X","master_sku":"UAT43-XL","available":[{"marketplace_name":"abc","doc_id":"QduDKpT2HqmuaFHRz"}]}]

const result = arr.find(obj => {
  return obj.available.some(el => el.doc_id === 'WCw8Hsyw4D3ab8TAZ');
});

console.log(result);