Datatables Checkbox Multi Select - javascript
I am using datatables v1.10 and i'm offering the user a number of select boxes in order to filter results. I want to filter the contents a specific column depending on their selection.
I'm building an inventory of volunteers that is searchable and discoverable by the local community.
They need to be able to filter on single and multiple values. So if they select Collection the table should display only results containing Collection. If they select Collection and Cleaning the table should display only results containing Collection and Cleaning (not Delivery). etc.
Currently my table only filters based on a single selection.
Here's a fiddle. Code also below;
Suggestions would be appreciated.
$(document).ready(function () {
var data = [
{
id: 1,
full_name: "Andrea Ragg",
email: "aragg0#netlog.com",
telephone: "584-78-0505",
location: "Derry",
service: "Collection",
availability: 0
},
{
id: 2,
full_name: "Thornton Keeri",
email: "tkeeri1#imageshack.us",
telephone: "503-58-8194",
location: "Cork",
service: "Collection, Cleaning, Delivery",
availability: 0
},
{
id: 3,
full_name: "Reuven Beddis",
email: "rbeddis2#china.com.cn",
telephone: "412-16-2320",
location: "Galway",
service: "Delivery, Collection",
availability: 0
},
{
id: 4,
full_name: "Phil Bardwall",
email: "pbardwall3#phpbb.com",
telephone: "864-82-5385",
location: "Cork",
service: "Collection, Cleaning, Delivery",
availability: 0
},
{
id: 5,
full_name: "Torey Jefford",
email: "tjefford4#seesaa.net",
telephone: "879-42-9577",
location: "Cork",
service: "Cleaning, Delivery",
availability: 1
},
{
id: 6,
full_name: "Chandler Robe",
email: "crobe5#biblegateway.com",
telephone: "299-07-6714",
location: "Derry",
service: "Collection",
availability: 0
},
{
id: 7,
full_name: "Rollie Boorn",
email: "rboorn6#g.co",
telephone: "358-94-3758",
location: "Derry",
service: "Delivery",
availability: 0
},
{
id: 8,
full_name: "Andie Daulton",
email: "adaulton7#nydailynews.com",
telephone: "776-32-4779",
location: "Derry",
service: "Collection, Cleaning, Delivery",
availability: 1
},
{
id: 9,
full_name: "Andonis Knagges",
email: "aknagges8#live.com",
telephone: "879-70-4074",
location: "Galway",
service: "Cleaning",
availability: 1
},
{
id: 10,
full_name: "Marney Moreinis",
email: "mmoreinis9#jalbum.net",
telephone: "324-76-8540",
location: "Dublin",
service: "Cleaning, Collection",
availability: 0
},
{
id: 11,
full_name: "Jean Drayson",
email: "jdraysona#biglobe.ne.jp",
telephone: "741-85-8028",
location: "Dublin",
service: "Cleaning, Collection, Delivery",
availability: 1
},
{
id: 12,
full_name: "Rhea Troubridge",
email: "rtroubridgeb#theguardian.com",
telephone: "342-47-7173",
location: "Dublin",
service: "Cleaning, Delivery",
availability: 1
},
{
id: 13,
full_name: "Cord Habergham",
email: "chaberghamc#columbia.edu",
telephone: "400-95-9506",
location: "Cork",
service: "Cleaning, Delivery, Collection",
availability: 0
},
{
id: 14,
full_name: "Otha Hiers",
email: "ohiersd#facebook.com",
telephone: "697-07-9372",
location: "Dublin",
service: "Cleaning, Delivery",
availability: 0
},
{
id: 15,
full_name: "Edna Barg",
email: "ebarge#wix.com",
telephone: "210-66-2867",
location: "Dublin",
service: "Cleaning, Collection, Delivery",
availability: 1
},
{
id: 16,
full_name: "Rozalin Wilmut",
email: "rwilmutf#freewebs.com",
telephone: "732-74-0848",
location: "Galway",
service: "Cleaning",
availability: 0
},
{
id: 17,
full_name: "Glen Darben",
email: "gdarbeng#google.com.au",
telephone: "570-01-5383",
location: "Galway",
service: "Cleaning, Collection, Delivery",
availability: 0
},
{
id: 18,
full_name: "Wally Longstaff",
email: "wlongstaffh#reference.com",
telephone: "278-18-3965",
location: "Belfast",
service: "Delivery",
availability: 1
},
{
id: 19,
full_name: "Moise Murrhardt",
email: "mmurrhardti#t.co",
telephone: "165-08-4136",
location: "Dublin",
service: "Delivery, Cleaning, Collection",
availability: 1
},
{
id: 20,
full_name: "Gloria Tedder",
email: "gtedderj#ucoz.ru",
telephone: "809-19-8763",
location: "Dublin",
service: "Delivery, Collection, Cleaning",
availability: 0
},
{
id: 21,
full_name: "Marthena Pavel",
email: "mpavelk#state.tx.us",
telephone: "180-16-5508",
location: "Derry",
service: "Cleaning",
availability: 1
},
{
id: 22,
full_name: "Livvy Tesoe",
email: "ltesoel#timesonline.co.uk",
telephone: "748-54-7269",
location: "Derry",
service: "Collection, Cleaning",
availability: 1
},
{
id: 23,
full_name: "Angelle Tondeur",
email: "atondeurm#ebay.com",
telephone: "761-27-3445",
location: "Galway",
service: "Cleaning, Collection",
availability: 1
},
{
id: 24,
full_name: "Marsiella Van Schafflaer",
email: "mvann#europa.eu",
telephone: "330-85-4309",
location: "Derry",
service: "Delivery, Cleaning",
availability: 1
},
{
id: 25,
full_name: "Norene Pettegree",
email: "npettegreeo#marketwatch.com",
telephone: "324-47-1541",
location: "Galway",
service: "Delivery",
availability: 0
},
{
id: 26,
full_name: "Gay Newcome",
email: "gnewcomep#free.fr",
telephone: "633-37-5490",
location: "Derry",
service: "Delivery, Cleaning",
availability: 1
},
{
id: 27,
full_name: "Karrah Peltzer",
email: "kpeltzerq#alibaba.com",
telephone: "785-01-1150",
location: "Belfast",
service: "Collection",
availability: 1
},
{
id: 28,
full_name: "Corrinne Gilli",
email: "cgillir#4shared.com",
telephone: "390-05-7538",
location: "Belfast",
service: "Collection",
availability: 1
},
{
id: 29,
full_name: "Jaymee Townrow",
email: "jtownrows#walmart.com",
telephone: "561-19-2949",
location: "Belfast",
service: "Delivery",
availability: 0
},
{
id: 30,
full_name: "Sarita Siggs",
email: "ssiggst#berkeley.edu",
telephone: "272-85-9311",
location: "Belfast",
service: "Delivery, Cleaning, Collection",
availability: 1
},
{
id: 31,
full_name: "Crissie Connerry",
email: "cconnerryu#bbb.org",
telephone: "429-41-7759",
location: "Belfast",
service: "Delivery",
availability: 1
},
{
id: 32,
full_name: "Pincus Olyfant",
email: "polyfantv#flickr.com",
telephone: "554-04-4124",
location: "Dublin",
service: "Cleaning",
availability: 1
},
{
id: 33,
full_name: "Joela Spearett",
email: "jspearettw#slashdot.org",
telephone: "249-42-3733",
location: "Cork",
service: "Collection, Cleaning",
availability: 0
},
{
id: 34,
full_name: "Teodora Floyd",
email: "tfloydx#pcworld.com",
telephone: "867-72-6127",
location: "Dublin",
service: "Cleaning, Collection",
availability: 0
},
{
id: 35,
full_name: "Sherrie Minall",
email: "sminally#google.co.uk",
telephone: "698-47-8076",
location: "Cork",
service: "Collection",
availability: 0
},
{
id: 36,
full_name: "Ikey Sowerby",
email: "isowerbyz#washingtonpost.com",
telephone: "428-82-5186",
location: "Dublin",
service: "Cleaning",
availability: 1
},
{
id: 37,
full_name: "Dasie Skelhorn",
email: "dskelhorn10#trellian.com",
telephone: "804-03-0371",
location: "Derry",
service: "Delivery, Collection, Cleaning",
availability: 0
},
{
id: 38,
full_name: "Wilburt Pickard",
email: "wpickard11#edublogs.org",
telephone: "130-53-6389",
location: "Cork",
service: "Delivery",
availability: 1
},
{
id: 39,
full_name: "Marven Poutress",
email: "mpoutress12#joomla.org",
telephone: "630-06-8139",
location: "Galway",
service: "Collection, Cleaning, Delivery",
availability: 0
},
{
id: 40,
full_name: "Sheff Ruck",
email: "sruck13#vinaora.com",
telephone: "132-51-1884",
location: "Derry",
service: "Collection",
availability: 1
},
{
id: 41,
full_name: "Hyacinth Botcherby",
email: "hbotcherby14#toplist.cz",
telephone: "861-11-1370",
location: "Belfast",
service: "Collection, Cleaning",
availability: 0
},
{
id: 42,
full_name: "Renato Jouhan",
email: "rjouhan15#yahoo.com",
telephone: "616-39-1823",
location: "Belfast",
service: "Delivery, Collection, Cleaning",
availability: 1
},
{
id: 43,
full_name: "Fayth Alwin",
email: "falwin16#unc.edu",
telephone: "887-35-7269",
location: "Dublin",
service: "Delivery, Collection",
availability: 0
},
{
id: 44,
full_name: "Hadrian Gatlin",
email: "hgatlin17#biblegateway.com",
telephone: "615-44-7488",
location: "Dublin",
service: "Delivery, Collection, Cleaning",
availability: 0
},
{
id: 45,
full_name: "Rois Fife",
email: "rfife18#deviantart.com",
telephone: "655-09-6453",
location: "Galway",
service: "Delivery",
availability: 1
},
{
id: 46,
full_name: "Pavlov Pactat",
email: "ppactat19#nature.com",
telephone: "261-25-9415",
location: "Cork",
service: "Delivery",
availability: 0
},
{
id: 47,
full_name: "Brocky Burnell",
email: "bburnell1a#blinklist.com",
telephone: "644-47-6112",
location: "Belfast",
service: "Delivery, Cleaning, Collection",
availability: 0
},
{
id: 48,
full_name: "Naoma Brimson",
email: "nbrimson1b#elpais.com",
telephone: "751-85-9640",
location: "Belfast",
service: "Delivery",
availability: 0
},
{
id: 49,
full_name: "Valma Reddoch",
email: "vreddoch1c#buzzfeed.com",
telephone: "110-89-6953",
location: "Derry",
service: "Collection, Delivery, Cleaning",
availability: 1
},
{
id: 50,
full_name: "Ebony Kilsby",
email: "ekilsby1d#engadget.com",
telephone: "604-37-4930",
location: "Belfast",
service: "Delivery",
availability: 1
}
];
dataTable = $("#example").DataTable({
data: data,
responsive: true,
//dom: '<"top"f>rt<"bottom"p><"clear">',
language: {
searchPlaceholder: "Search records"
},
columns: [
{ data: "id" },
{ data: "full_name" },
{ data: "email" },
{ data: "telephone" },
{ data: "location" },
{ data: "service" },
{
data: "availability",
render: function (data, type, row, meta) {
if (data === 0) {
return '<span class="badge badge-secondary">busy</span>'
;
}
if (data === 1) {
return '<span class="badge badge-success">available</span>'
;
}
}
}
],
columnDefs: [
{
targets: [0, 2, 3, 5],
orderable: false
}
]
});
$('.filter-checkbox').on('change', function(e){
var searchTerms = []
$.each($('.filter-checkbox'), function(i,elem){
if($(elem).prop('checked')){
searchTerms.push("^" + $(this).val() + "$")
}
})
dataTable.column(5).search(searchTerms.join('|'), true, false, true).draw();
});
});
.filter-checkbox{
margin-left: 30px
}
.filter-checkbox:first-child{
margin-left:0
}
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
<div class="container">
<div class="row">
<div class="col py-3 text-center">
<h2>Community Connect</h2>
<p class="lead text-muted">Table will filter as you type.</p>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="filter-wrapper">
<input type="checkbox" class="filter-checkbox" value="collection"/> Collection
<input type="checkbox" class="filter-checkbox" value="delivery"/> Delivery
<input type="checkbox" class="filter-checkbox" value="cleaning"/> Cleaning
</div>
</div>
</div>
<div class="row">
<div class="col py-3">
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Location</th>
<th>Service Offered</th>
<th>Availability</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
Add hidden columns for each checkbox value with something as simple as a true/false in that column. Then you can have each checkbox filter against their column and set the value to filter by based on whether the checkbox is checked. While you adding more columns, it makes the filtering simple.
A more complex solution is to use a multi-select on a single column, likely hidden, and dynamically build a regex to filter the column. I use this for a dynamic multi-select option list, but since your options seem static, the hidden columns seems like an easier approach.
Related
get the indexOf of a cascaded array of objects
I'm trying and puzzling for a couple of hours now and I can't get my head around it. I have the following data structure in Redux: entities: { users: { dentists: [ { id: 1, first_name: 'Tessa', last_name: 'Iiannone', phone: '+234 325 319 4277', email: 'tiiannone0#dentistcompanybvt.com' }, { id: 2, first_name: 'Kennett', last_name: 'Pedreschi', phone: '+48 204 144 9885', email: 'kpedreschi1#dentistcompanybvt.com' }, { id: 3, first_name: 'Lorine', last_name: 'Tolle', phone: '+670 691 959 9810', email: 'ltolle2#dentistcompanybvt.com' }, { id: 4, first_name: 'Nessi', last_name: 'Pikhno', phone: '+995 756 907 2258', email: 'npikhno3#dentistcompanybvt.com' } ], assistants: [ { id: 1, first_name: 'Nickolas', last_name: 'Seamans', phone: '+62 949 597 4013', email: 'nseamans0#dentistcompanybvt.com' }, { id: 2, first_name: 'Peri', last_name: 'Helversen', phone: '+51 886 232 9275', email: 'phelversen1#dentistcompanybvt.com' } ], clients: [ { id: 1, first_name: 'Mona', last_name: 'Shakelade', phone: '+63 475 243 2059', email: 'mshakelade0#sourceforge.net', date_of_birth: '26/01/1987', status: null }, { id: 2, first_name: 'Dario', last_name: 'Aizikovitz', phone: '+33 454 959 7355', email: 'daizikovitz1#buzzfeed.com', date_of_birth: '16/08/1999', status: null }, { id: 3, first_name: 'Caren', last_name: 'Chidgey', phone: '+358 905 256 6974', email: 'cchidgey2#imgur.com', date_of_birth: '08/03/1983', status: null }, { id: 4, first_name: 'Timmi', last_name: 'Weond', phone: '+225 796 207 5915', email: 'tweond3#dion.ne.jp', date_of_birth: '25/08/1972', status: null }, { id: 5, first_name: 'Greer', last_name: 'Cornelius', phone: '+46 793 784 2482', email: 'gcornelius4#ask.com', date_of_birth: '29/03/1968', status: null }, { id: 6, first_name: 'Catlee', last_name: 'Elmar', phone: '+33 826 857 9849', email: 'celmar5#economist.com', date_of_birth: '25/11/1976', status: null }, { id: 7, first_name: 'Ilsa', last_name: 'Tynnan', phone: '+591 283 830 4992', email: 'itynnan6#illinois.edu', date_of_birth: '19/02/1992', status: null }, { id: 8, first_name: 'Delia', last_name: 'Blueman', phone: '+55 392 389 4499', email: 'dblueman7#printfriendly.com', date_of_birth: '09/11/1975', status: null }, { id: 9, first_name: 'Lorilyn', last_name: 'Semens', phone: '+7 271 804 0493', email: 'lsemens8#zimbio.com', date_of_birth: '17/03/2001', status: null }, { id: 10, first_name: 'Lorilee', last_name: 'Slemmonds', phone: '+63 858 699 0861', email: 'lslemmonds9#umich.edu', date_of_birth: '20/07/1991', status: null } ] }, appts: { id: 1, date: '01012022', hour: 8, client_id: 1, dentist_id: 1, assistant_id: 1 }, ui: { ids: [ 1 ], entities: { '1': { id: 1, usertype: 'client' } } } } } I combined the 3 lists in my slice with: const users = { dentists: dentists, assistants: assistants, clients: clients }; So now i expect that when i say: const index = users.clients.indexOf((user) => user.id === action.payload.id) ...wil give me the index of the matching item with action.payload.id, but I'll keep on getting -1 when I do a console.log(index) what means that there is no match. Can anyone help me out here? What am I doing wrong?
indexOf requires an element. You can use find to get the element first and get the index next: console.log(users.clients.indexOf(users.clients.find(client => client.id === action.payload.id))); findIndex requires a callback, which is the requirement in your case, as you look for an object that you don't know, but can find by id: console.log(users.clients.findIndex((client) => client.id == action.payload.id));
A simple methodology to merge Array of the nested object into an array of the same object
I'm looking for a simple methodology to merge the Array of the nested object into an array of the same object Input: const data=[ { id: 123, name: "dave", age: 23 , address:{city:"chennai", zipcode:600001}}, { id: 456, name: "chris", age: 23, address:{city:"cbe", zipcode:600002} }, { id: 789, name: "bob", age: 23, address:{city:"tiruppur", zipcode:600003}}, { id: 101, name: "tom", age: 23, address:{city:"erode", zipcode:600004} }, { id: 102, name: "tim", age: 23, address:{city:"selam", zipcode:600005} } ] Needed Output: { id: 123, name: "dave", age: 23, city:"chennai", zipcode:600001}, { id: 456, name: "chris", age: 23, city:"cbe", zipcode:600002}, { id: 789, name: "bob", age: 23, city:"tiruppur", zipcode:600003}, { id: 101, name: "tom", age: 23, city:"erode", zipcode:600004}, { id: 102, name: "tim", age: 23, city:"selam", zipcode:600005} ]
Use a combination of destructuring and spread syntax: const data=[{ id: 123, name: "dave", age: 23 , address:{city:"chennai", zipcode:600001}},{ id: 456, name: "chris", age: 23, address:{city:"cbe", zipcode:600002} },{ id: 789, name: "bob", age: 23, address:{city:"tiruppur", zipcode:600003}},{ id: 101, name: "tom", age: 23, address:{city:"erode", zipcode:600004} },{ id: 102, name: "tim", age: 23, address:{city:"selam", zipcode:600005} }]; const result = data.map(({address, ...rest}) => ({...rest, ...address})); console.log(result);
You can use Object.entries to extract each property and its value in the address property and assign it to the parent object, then delete the address property. const data=[{id:123,name:"dave",age:23,address:{city:"chennai",zipcode:600001}},{id:456,name:"chris",age:23,address:{city:"cbe",zipcode:600002}},{id:789,name:"bob",age:23,address:{city:"tiruppur",zipcode:600003}},{id:101,name:"tom",age:23,address:{city:"erode",zipcode:600004}},{id:102,name:"tim",age:23,address:{city:"selam",zipcode:600005}}]; const result = data.map(e => (Object.entries(e.address).forEach(f => e[f[0]] = f[1]), delete e.address, e)) console.log(result)
let data = [ { id: 123, name: "dave", age: 23, address: { city: "chennai", zipcode: 600001 } }, { id: 456, name: "chris", age: 23, address: { city: "cbe", zipcode: 600002 } }, { id: 789, name: "bob", age: 23, address: { city: "tiruppur", zipcode: 600003 } }, { id: 101, name: "tom", age: 23, address: { city: "erode", zipcode: 600004 } }, { id: 102, name: "tim", age: 23, address: { city: "selam", zipcode: 600005 } } ] data = data.map((node) => ({ id: node.id, name: node.name, age: node.age, city: node.address.city, zipcode: node.address.zipcode })) console.log(data)
const data=[ { id: 123, name: "dave", age: 23 , address:{city:"chennai", zipcode:600001}}, { id: 456, name: "chris", age: 23, address:{city:"cbe", zipcode:600002} }, { id: 789, name: "bob", age: 23, address:{city:"tiruppur", zipcode:600003}}, { id: 101, name: "tom", age: 23, address:{city:"erode", zipcode:600004} }, { id: 102, name: "tim", age: 23, address:{city:"selam", zipcode:600005} } ]; const result = data.map(item => ({id: item.id, name: item.name, age: item.age, ...item.address})); console.log(result);
Write a function to get customers, just pass the addressid and read all it's customers? parameter (addressId)
Javascript As You can see my javascript code Im trying to get customers based on the address id. I'm struggling to get customers based on the address. var customers = [ { id: 1, name: "Customer1", email: "customer1#test.com", addresses: [1, 5, 3, 10] }, { id: 2, name: "Customer2", email: "customer2#test.com", addresses: [2, 8, 10] }, { id: 3, name: "Customer3", email: "customer3#test.com", addresses: [5, 2] }, { id: 4, name: "Customer4", email: "customer4#test.com", addresses: [3, 7, 8] }, { id: 5, name: "Customer5", email: "customer5#test.com", addresses: [4, 6, 9] }, ]; var addresses = [ { id: 1, street: "Riche street", city: "TPT", pin: "232434" }, { id: 2, street: "Cross street", city: "Vellore", pin: "75646456" }, { id: 3, street: "Colony", city: "Chennai", pin: "7887878" }, { id: 4, street: "Annai Nagar", city: "Bangalore", pin: "43545" }, { id: 5, street: "Main Bazar", city: "Salem", pin: "4567767" }, { id: 6, street: "Gandhi Nagar", city: "Hosur", pin: "232434" }, { id: 7, street: "Gandhi Nagar", city: "Pondicherry", pin: "75646456" }, { id: 8, street: "Colony", city: "Krishanagiri", pin: "7887878" }, { id: 9, street: "Annai Nagar", city: "Ambur", pin: "43545" }, { id: 10, street: "Main Bazar", city: "Vaniyambadi", pin: "4567767" }, ]; function getCustomers(get_id) { var arr = []; for (var i = 0; i < addresses.length; i++) { if (get_id == addresses[i].id) { console.log(addresses[i].id); for (var prop in customers) { if (customers.hasOwnProperty(prop)) { if ( prop.addresses.filter((x) => { x == addresses[i].id; }) ) { console.log(prop); } } } } } } getCustomers(10); I thing I missing something here... If I pass 10 as as parameter it will fetch the customer records who are belongs to addresses 10. Output well be: { id: 1, name: "Customer1", email: "customer1#test.com", addresses: [1,5,3,10] }, { id: 2, name: "Customer2", email: "customer2#test.com", addresses: [2,8,10] },
Here is a function that returns a list of customers based on the address ID passed: function getCustomers(addressId) { return customers.filter(customer => { return customer.addresses.includes(addressId); }); }
Here You Go let obj = [ { id: 1, name: "Customer1", email: "customer1#test.com", addresses: [1,5,3,10] }, { id: 2, name: "Customer2", email: "customer2#test.com", addresses: [2,8,10] }, { id: 3, name: "Customer2", email: "customer2#test.com", addresses: [2,8,5] }, { id: 5, name: "Customer2", email: "customer2#test.com", addresses: [6, 8, 9] }, ] function getCustomers(data, id) { //data will be your object from which to find id let customers = []; data.forEach(function(d) { d.addresses.forEach(function(a) { if (a == id) { customers.push(d); } }); }); return customers; } note: this function will return you values as array of objects
I'm getting empty array what is wrong?
I want the universities that have the string "Uni" included in their name. then, Create a new array called uni that contains them all. I've use the HOF method still didn't work. var graduates = [{ id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" }, { id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" }, { id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" }, { id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" }, { id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" }, { id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" }, { id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com" }] const unisWithUni = []; console.log(unisWithUni); for (let i = 0; i < graduates.length; i++) { if (graduates[i].university === "Uni") { unisWithUni.push(graduates[i]); } }
You should change graduates[i].university === "Uni" to graduates[i].university.includes("Uni") this way any string that contains 'Uni' will be found, otherwise it will only match exactly "Uni". Also, put your console.log(unisWithUni); after the for loop. var graduates = [{ id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" }, { id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" }, { id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" }, { id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" }, { id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" }, { id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" }, { id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com" }] const unisWithUni = []; for (let i = 0; i < graduates.length; i++) { if (graduates[i].university.includes("Uni")) { unisWithUni.push(graduates[i]); } } console.log(unisWithUni);
You are comparing a complete string. In javascript (or almost any language) "equal" don't means "contains". So "hi" === "hi what's up" is not the same, they are not equal. In JavasSript you want to look for indexOf() (old&new browsers) or includes() (new browsers), so: var graduates = [ { id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" }, { id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" }, { id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" }, { id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" }, { id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" }, { id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" }, { id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com"} ]; const unisWithUni = []; for (let i = 0; i < graduates.length; i++) { if (graduates[i].university.indexOf("Uni") > -1) { unisWithUni.push(graduates[i]); } } console.log(unisWithUni);
Here is an example that uses jQuery's map(). Why, just because. Note that I convert the university to lowercase before searching for the string uni making the search case insensitive. var graduates = [{ id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" }, { id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" }, { id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" }, { id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" }, { id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" }, { id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" }, { id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com" } ]; var unisWithUni = $.map(graduates, grad => { return grad.university.toLowerCase().includes("uni") ? grad : null; }); console.log(unisWithUni); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
How to add a value to a JSON array of objects?
i have a json array of objects like this, to pass the values to the datatables. [{ _id: '58a2b5941a9dfe3537aad540', Country: 'India', State: 'Andhra Pradesh', District: 'Guntur', Division: '', Village: 'Macharla', FarmerName: 'Vijay', Address: '', Pin: '', PrimaryContact: '9160062222', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' }, { _id: '58a2b5941a9dfe3537aad541', Country: 'India', State: 'Telangana', District: 'Karimnagar', Division: '', Village: 'Sirisilla', FarmerName: 'Subhash Rao', Address: '', Pin: '', PrimaryContact: '8121787878/9441967878', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' }, { _id: '58a2b5941a9dfe3537aad542', Country: 'India', State: 'Telangana', District: 'Medak', Division: '', Village: 'Jagur', FarmerName: 'Ramachandra', Address: '', Pin: '', PrimaryContact: '9346481116', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' }, { _id: '58a2b5941a9dfe3537aad543', Country: 'India', State: 'Telangana', District: 'Mahaboob Nagar', Division: '', Village: 'annugal', FarmerName: 'Rajesh Reddy', Address: '', Pin: '', PrimaryContact: '93464593808', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' } ] Now i want to add one more object like "recordsTotal":600 outside of this array. how can i achieve it? Finally i want the data like this { "draw": 1, "recordsTotal": 1, "recordsFiltered": 1, "data": [{ "VendorID": "V0000051", "Name": "STAPLES CONTRACT AND COMMERCIAL INC", "Mnemonic": "CORPORATE", "TermsDescription": "INV 2/30 NET 31", "ActiveYn": "Y" }] }
First of all store the json array in a variable like var datalist=[{ _id: '58a2b5941a9dfe3537aad540', Country: 'India', State: 'Andhra Pradesh', District: 'Guntur', Division: '', Village: 'Macharla', FarmerName: 'Vijay', Address: '', Pin: '', PrimaryContact: '9160062222', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' }, { _id: '58a2b5941a9dfe3537aad541', Country: 'India', State: 'Telangana', District: 'Karimnagar', Division: '', Village: 'Sirisilla', FarmerName: 'Subhash Rao', Address: '', Pin: '', PrimaryContact: '8121787878/9441967878', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' }, { _id: '58a2b5941a9dfe3537aad542', Country: 'India', State: 'Telangana', District: 'Medak', Division: '', Village: 'Jagur', FarmerName: 'Ramachandra', Address: '', Pin: '', PrimaryContact: '9346481116', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' }, { _id: '58a2b5941a9dfe3537aad543', Country: 'India', State: 'Telangana', District: 'Mahaboob Nagar', Division: '', Village: 'annugal', FarmerName: 'Rajesh Reddy', Address: '', Pin: '', PrimaryContact: '93464593808', OtherContacts: '', Email: '', updatedAt: '2017-02-14T04:39:01.000Z', modifiedBy: '', createdAt: '2017-02-14T04:39:01.000Z' } ] then declare another json object and initialize values like var FinalJsonObject={"draw": 1, "recordsTotal": 1, "recordsFiltered": 1, "data": datalist}