我有这样的数据结构
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"
}
]
}
如何获得指定的输出。预先感谢。
答案 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);