I have data that is stored in JS array of objects. Please see example below.
const data = [
{"company": 5, "office": 3355, "section": "00045"},
{"company": 2, "office": 4322, "section": "00008"},
{"company": 3, "office": 3355, "section": "00124"},
{"company": 4, "office": 8907, "section": "00023"},
{"company": 10, "office": 4322, "section": "00008"},
{"company": 10, "office": 6778, "section": "00004"},
{"company": 3, "office": 3355, "section": "00012"},
{"company": 2, "office": 6778, "section": "00098"},
{"company": 9, "office": 3355, "section": "00077"},
{"company": 10, "office": 6778, "section": "00055"}
];
User interface looks like this:
$("#btn-filter").on("click", function() {
let company = $("#company").val().trim();
let office = $("#office").val().trim();
let section = $("#section").val().trim();
$("#company").val(company);
$("#office").val(office);
$("#section").val(section);
if (company == '' && office == '' && section == '') {
alert("At least one field must be entered.");
return;
}
let data = filterData(company, office, section);
console.log(data);
});
function filterData(company, office, section) {
let filtered_data = app_data.find(function(idx) {
return idx.company || idx.office || idx.section;
});
return filtered_data;
};
const app_data = [
{"company": 5, "office": 3355, "section": "00045"},
{"company": 2, "office": 4322, "section": "00008"},
{"company": 3, "office": 3355, "section": "00124"},
{"company": 4, "office": 8907, "section": "00023"},
{"company": 10, "office": 4322, "section": "00008"},
{"company": 10, "office": 6778, "section": "00004"},
{"company": 3, "office": 3355, "section": "00012"},
{"company": 2, "office": 6778, "section": "00098"},
{"company": 9, "office": 3355, "section": "00077"},
{"company": 10, "office": 6778, "section": "00055"}
];
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form-group bg-light no-gutters py-2">
<label for="company">Company:</label>
<div><input id="company" placeholder="Enter Company #"></div>
<label for="office">Office:</label>
<div><input id="office" placeholder="Enter Office #"></div>
<label for="section">Section:</label>
<div><input id="section" placeholder="Enter Section #"></div>
<div><button id="btn-filter">Filter</button></div>
</div>
The example above should return filtered data in the console. User has an option to filter only on one filed or more. If user only enters company and section only matching records should return. So far I was not able to get this to work properly. Doesn't matter what I enter in the search criteria always one record is returned. I'm wondering if there is an easy way to achieve this in JavaScript. Thanks.
findmethod only returns 1 record. you should usefilterinstead.