搜索嵌套对象的数组,如果在子中找到值,则返回父对象
这个问题在这里已经有了答案:
您可以使用迭代和递归方法并返回检查结果,并在子节点匹配搜索值时构建新的对象和数组。
function getValue(item) {
if (Array.isArray(item)) {
return item.reduce(iterA, undefined);
}
if (item && typeof item === 'object') {
return iterO(item);
}
if (typeof item !== 'object' && item.toString().toLowerCase().indexOf(search) !== -1) {
return item;
}
}
function iterO(o) {
var temp = Object.keys(o).reduce(function (r, k) {
var value = getValue(o[k]);
if (value) {
r = r || {};
r[k] = value;
}
return r;
}, undefined);
if (temp) {
Object.keys(o).forEach(function (k) {
if (!(k in temp)) {
temp[k] = o[k];
}
});
}
return temp;
}
function iterA(r, a) {
var value = getValue(a);
if (value) {
r = r || [];
r.push(value);
}
return r;
}
var data = [{ booking_name: "gtec/1101822/lmikdy/ls-rmea/oss11", asset_count: 2, pdg: "Invalid", user_area: "Invalid", deployment_number: "Invalid", spoc: "invalid", release: "Invalid", start_date: "2017-06-12 00:00:00", end_date: "2017-06-16 00:00:00", asset_info: [{ bams_id: "BAMS-1001423507", hostname: "GTVOSS11", status: 10, site_location: "IEAT01 Tipperary", rack_number: "VIRTUAL RACK", rack_u_position: 0, manufacturer: "EMC", model: "VM" }, { bams_id: "BAMS-1001368001", hostname: "None", status: 10, site_location: "IEAT01 Tipperary", rack_number: "VIRTUAL RACK", rack_u_position: 0, manufacturer: "HP", model: "HP BL460C GEN8" }], full_name: "Invalid (invalid)", email_address: "Invalid" }, { booking_name: "gtec/1101822/lmikdy/ls-rmea/oss11", asset_count: 2, pdg: "Invalid", user_area: "Invalid", deployment_number: "Invalid", spoc: "invalid", release: "Invalid", start_date: "2017-06-12 00:00:00", end_date: "2017-06-16 00:00:00", asset_info: [{ bams_id: "BAMS-1001423507", hostname: "GTVOSS11", status: 10, site_location: "IEAT01 Tipperary", rack_number: "VIRTUAL RACK", rack_u_position: 0, manufacturer: "EMC", model: "VM" }], full_name: "Invalid (invalid)", email_address: "Invalid" }],
search = 'emc',
result = data.reduce(iterA, undefined);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
链接地址: http://www.djcxy.com/p/55325.html
上一篇: search array of nested objects and return parent if value is found in child