Related
Currently, I have an array in Javascript named locations, described below:
let locations = [
{
"id": "1",
"city": "Kermit",
"state": "TX",
},
{
"id": "2",
"city": "Bloomington",
"state": "MN",
},
{
"id": "3",
"city": "Pauls Valley",
"state": "OK",
},
{
"id": "4",
"city": "Colville",
"state": "WA",
},
{
"id": "5",
"city": "Jacksboro",
"state": "TX",
},
{
"id": "6",
"city": "Shallowater",
"state": "TX"
}
]
using Javascript, I need to create another array from this array by filtering out the cities with the same states as a single array within the locations array.
required output:
locations = [
TX:[{
"id": "1",
"city": "Kermit",
"state": "TX",
},
{
"id": "5",
"city": "Jacksboro",
"state": "TX",
},
{
"id": "6",
"city": "Shallowater",
"state": "TX"
}
],
MN:[
{
"id": "2",
"city": "Bloomington",
"state": "MN",
},
],
OK:[
{
"id": "3",
"city": "Pauls Valley",
"state": "OK",
},
],
WA:[
{
"id": "4",
"city": "Colville",
"state": "WA",
},
]
]
Also, I need this array sorted in alphabetical order. If some one could give me a good approach to solve this scenario, it would be a great help.
const locations = [
{ "id": "1", "city": "Kermit", "state": "TX" },
{ "id": "2", "city": "Bloomington", "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville", "state": "WA" },
{ "id": "5", "city": "Jacksboro", "state": "TX" },
{ "id": "6", "city": "Shallowater", "state": "TX" }
];
const byState = {};
[...locations].sort((a,b) =>
a.state.localeCompare(b.state) || a.city.localeCompare(b.city)
).forEach(i => (byState[i.state]??=[]).push(i));
console.log(byState);
You can reduce the locations into groups by state. Once you have achieved that, you can convert the object key-value pairs to entries, sort them, and then convert them back into an object.
const locations = [
{ "id": "1", "city": "Kermit", "state": "TX" },
{ "id": "2", "city": "Bloomington", "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville", "state": "WA" },
{ "id": "5", "city": "Jacksboro", "state": "TX" },
{ "id": "6", "city": "Shallowater", "state": "TX" }
];
const sortObjectKeys = (obj) =>
Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
const groupedByState = sortObjectKeys(
locations.reduce((acc, location) => ({
...acc,
[location.state]: [...(acc[location.state] ?? []), {
...location
}]
}), {}));
console.log(groupedByState);
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to forgo sorting, just reduce the data:
const locations = [
{ "id": "1", "city": "Kermit", "state": "TX" },
{ "id": "2", "city": "Bloomington", "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville", "state": "WA" },
{ "id": "5", "city": "Jacksboro", "state": "TX" },
{ "id": "6", "city": "Shallowater", "state": "TX" }
];
const groupedByState =
locations.reduce((acc, { state, ...location }) => ({
...acc,
[state]: [...(acc[state] ?? []), { ...location, state }]
}), {});
console.log(groupedByState);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I've JSON array which is returned after an edit success in react-redux-saga. The record I updated before and after successfull update comes together as an element of JSON array. So, I need to replace the old resort element with the newly updated resort values and also delete the old resort.
Here, in this example, I have updated resortId(id)=15, but my redux-saga returns both-old resort and the updated new resort,clubbed together in a single element in JSON array cuz in the this.props(cuz place part in this id=15 belongs to another saga store).
resortafterupdate=[{
"id": 5,
"name": "The Ananta Udaipur",
"address": "Village Bujhda,Tehsil Girwa",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "string",
"phone": "567890055"
}, {
"id": 10,
"name": "Test",
"address": "Raj Garden road111",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "986289"
}, {
"id": 11,
"name": "bbbbb",
"address": "ggjgjgjh",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "jjkhkhkhk",
"phone": "89789789"
}, {
"id": 12,
"name": "The Classic",
"address": "chandni chowk",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "beverages",
"phone": "687686868"
}, {
"id": 9,
"name": "xyzzzz 56788998877666",
"address": "111111223345566Raj Garden road111",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "afafas asdfasfas",
"phone": "11111111111"
}, {
"id": 13,
"name": "Byculla Navi ln",
"address": "Byculla Navi ln",
"placeId": 3,
"city": "Puducherry",
"state": "Puducherry",
"country": "India",
"details": "beverages",
"phone": "04409"
}, {
"id": 8,
"name": "test address",
"address": "Raj Garden road111",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "afafas asdfasfas",
"phone": "3253453434"
}, {
"id": 7,
"name": "test name",
"address": "test address",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "9862897999"
},
{
"resort": {
"id": 15,
"name": "AAA",
"address": "hjhgkjk",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "jhkhkjhkjhkjh",
"phone": "98789797"
},
"id": 15,
"name": "BBB",
"address": "NewTown",
"details": "jhkhkjhkjhkjh",
"phone": "98789797",
"place": {
"id": 3,
"city": "Puducherry",
"country": "India",
"state": "Puducherry"
}
}
]
How do I delete the child element resort with id=15 as this is old record before the update? And how do I rename the id of "place" to "placeId" and merge the inner parts - placeId,city,state and country to the outer part of the element - name=BBB and Id=15 and address": "NewTown","details": "jhkhkjhkjhkjh","phone": "98789797" to something like this
resortafterupdate=[{
"id": 5,
"name": "The Ananta Udaipur",
"address": "Village Bujhda,Tehsil Girwa",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "string",
"phone": "567890055"
}, {
"id": 10,
"name": "Test",
"address": "Raj Garden road111",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "986289"
}, {
"id": 11,
"name": "bbbbb",
"address": "ggjgjgjh",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "jjkhkhkhk",
"phone": "89789789"
}, {
"id": 12,
"name": "The Classic",
"address": "chandni chowk",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "beverages",
"phone": "687686868"
}, {
"id": 9,
"name": "xyzzzz 56788998877666",
"address": "111111223345566Raj Garden road111",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "afafas asdfasfas",
"phone": "11111111111"
}, {
"id": 13,
"name": "Byculla Navi ln",
"address": "Byculla Navi ln",
"placeId": 3,
"city": "Puducherry",
"state": "Puducherry",
"country": "India",
"details": "beverages",
"phone": "04409"
}, {
"id": 8,
"name": "test address",
"address": "Raj Garden road111",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "afafas asdfasfas",
"phone": "3253453434"
}, {
"id": 7,
"name": "test name",
"address": "test address",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "9862897999"
},
{
"id": 15,
"name": "AAA",
"address": "hjhgkjk",
"details": "jhkhkjhkjhkjh",
"phone": "98789797",
"placeId": 3,
"city": "Puducherry",
"country": "India",
"state": "Puducherry"
}
]
I have deleted the "resort" but unable to rename id in place part to placeId and merge it to the outer element.
function deleteKey(obj, keyToDelete) {
Object.keys(obj).forEach(key => {
if (key.toLowerCase() === keyToDelete) {
delete obj[key];
}
value = obj[key];
if (value instanceof Object) {
deleteKey(value, keyToDelete);
}
});
}
deleteKey(resortafterupdate, "resort");
I found a solution to flatten the child props using this answe on this link
Solution
Here's the code I modified according to my needs
function deleteKey(obj, keyToDelete) {
Object.keys(obj).forEach(key => {
if (key.toLowerCase() === keyToDelete) {
delete obj[key];
}
value = obj[key];
if (value instanceof Object) {
deleteKey(value, keyToDelete);
}
});
}
Object.flatten = function(data){
var resultMain = [];
var result = {};
function recurse(cur, prop){
if (Object(cur) !== cur){
result[prop] = cur;
}else if(Array.isArray(cur)){
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop);
if(l == 0)
result[prop] = [];
}else{
var isEmpty = true;
for(var p in cur){
isEmpty = false;
recurse(cur[p], prop==="place" && p==="id"? prop+"Id" : p);
}
if(isEmpty && prop)
result[prop] = {};
}
}
for(var i=0; i<data.length; i++){
result = {};
recurse(data[i], "");
resultMain[i] = result;
}
return resultMain;
}
deleteKey(updateResorts, "resort");
console.log(Object.flatten(newlyaddedResort));
I have a ASP.Net hidden field which has data in JSON format as shown below
[
{
"RegionName": "USA",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "8888",
"Country": "USA",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Test",
"Email": "Test#test.com",
"Phone": "9998887777"
}
},
{
"RegionName": "Mexico",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "33333",
"Country": "Mexico",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Amex",
"Email": "test#test.com",
"Phone": "9998887777"
}
}
]
which is read in Javascript using below code
var value = $('#countryInvoice')[0].defaultValue;
Now I want to search this JSON using javascript based on Region name and delete the record from the hidden field. So I want to remove the data point for say USA so only the below remains
[
{
"RegionName": "Mexico",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "33333",
"Country": "Mexico",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Amex",
"Email": "test#test.com",
"Phone": "9998887777"
}
}
]
Can someone please tell me how to do it in JQuery or Javascript.
Thanks
//ES5
var res = value.filter(function(e) { return e["RegionName"] != "USA"; })
//ES6
var res = value.filter(e => e["RegionName"] != "USA")
Note: The Arrow function is ES6 syntax.
You just need to filter it out using Array.prototype.filter().
Check out the MDN Docs here
The snippet below filters out USA
let value = [{
"RegionName": "USA",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "8888",
"Country": "USA",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Test",
"Email": "Test#test.com",
"Phone": "9998887777"
}
},
{
"RegionName": "Mexico",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "33333",
"Country": "Mexico",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Amex",
"Email": "test#test.com",
"Phone": "9998887777"
}
}
];
let newArray = value.filter(arr => arr.RegionName !== 'USA');
console.log(newArray);
I have created a search box, which the user enters a name or id in the search form input box and it returns the result . Only problem it works only once.
Here is my HTML below
<button id="basic-search" class="btn btn-default " type="button" > <span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
<input type="text" id="basicsearchVal" class="form-control" placeholder="Enter text,." autocomplete="on">
I then pass the entered value "searchInput" as a querystring url to the jQgrid
var searchInput = $("#basicsearchVal").val()
SearchData =newURL +"/services-monitor/GetQuickSearch?searchString="+searchInput;
When the user searches, it return the result the first time. but when I try to enter a new name or number in the search form box second time, the jqgrid doesnt seem to update the result, it just show the old result, even though i can see the updated user submitted value is being passed correctly to the JQgrid ajax call.
Only if I refresh the page manually every time it return the result
I also added this as per examples online.:
$(".search-result").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
jQuery(".search-result").trigger("reloadGrid");
what can I do to fix this? why wont JQgrid reload and display the updated results?
Here my JS CODE and FIDDLE
var jsonData = [{
"Id": 919,
"CertificateNumber": "4829",
"Name": "1880 Bank",
"FullName": "1880 Bank",
"address": "304 HIGH STREET",
"city": "CAMBRIDGE",
"state": "MD",
"zip": "21613"
}, {
"Id": 6020,
"CertificateNumber": "57899",
"Name": "1st Advantage Bank",
"FullName": "1st Advantage Bank",
"address": "240 SALT LICK ROAD",
"city": "SAINT PETERS",
"state": "MO",
"zip": "63376"
}, {
"Id": 3817,
"CertificateNumber": "22039",
"Name": "1st Bank",
"FullName": "1st Bank",
"address": "201 NORTH WILBUR AVE",
"city": "BROADUS",
"state": "MT",
"zip": "59317"
}, {
"Id": 3054,
"CertificateNumber": "16419",
"Name": "1st Bank & Trust",
"FullName": "1st Bank & Trust",
"address": "710 SOUTH PARK DRIVE",
"city": "BROKEN BOW",
"state": "OK",
"zip": "74728"
}, {
"Id": 4843,
"CertificateNumber": "30367",
"Name": "1st Bank of Sea Isle City",
"FullName": "1st Bank of Sea Isle City",
"address": "4301 LANDIS AVENUE",
"city": "SEA ISLE CITY",
"state": "NJ",
"zip": "08243"
}, {
"Id": 5817,
"CertificateNumber": "57298",
"Name": "1st Bank Yuma",
"FullName": "1st Bank Yuma",
"address": "2799 SOUTH 4TH AVENUE",
"city": "YUMA",
"state": "AZ",
"zip": "85364"
}, {
"Id": 5031,
"CertificateNumber": "32487",
"Name": "1st Cameron State Bank",
"FullName": "1st Cameron State Bank",
"address": "124 SOUTH WALNUT",
"city": "CAMERON",
"state": "MO",
"zip": "64429"
}, {
"Id": 6278,
"CertificateNumber": "58485",
"Name": "1st Capital Bank",
"FullName": "1st Capital Bank",
"address": "5 HARRIS COURT, BLDG N, # NO",
"city": "MONTEREY",
"state": "CA",
"zip": "93940"
}, {
"Id": 5942,
"CertificateNumber": "57657",
"Name": "1st Century Bank, National Association",
"FullName": "1st Century Bank, National Association",
"address": "1875 CENTURY PARK EAST, # 14",
"city": "LOS ANGELES",
"state": "CA",
"zip": "90067"
}, {
"Id": 5666,
"CertificateNumber": "35456",
"Name": "1st Colonial Community Bank",
"FullName": "1st Colonial Community Bank",
"address": "1040 HADDON AVENUE",
"city": "COLLINGSWOOD",
"state": "NJ",
"zip": "08108"
}, {
"Id": 2116,
"CertificateNumber": "11706",
"Name": "1st Community Bank",
"FullName": "1st Community Bank",
"address": "407 THIRD STREET",
"city": "SHERRARD",
"state": "IL",
"zip": "61281"
}, {
"Id": 4381,
"CertificateNumber": "27552",
"Name": "1st Constitution Bank",
"FullName": "1st Constitution Bank",
"address": "2650 ROUTE 130",
"city": "CRANBURY",
"state": "NJ",
"zip": "08512"
}, {
"Id": 5327,
"CertificateNumber": "34393",
"Name": "1st Equity Bank",
"FullName": "1st Equity Bank",
"address": "3956 WEST DEMPSTER STREET",
"city": "SKOKIE",
"state": "IL",
"zip": "60076"
}, {
"Id": 5928,
"CertificateNumber": "57611",
"Name": "1st Equity Bank Northwest",
"FullName": "1st Equity Bank Northwest",
"address": "1330 DUNDEE ROAD",
"city": "BUFFALO GROVE",
"state": "IL",
"zip": "60089"
}, {
"Id": 326,
"CertificateNumber": "1673",
"Name": "1st Financial Bank USA",
"FullName": "1st Financial Bank USA",
"address": "331 N. DAKOTA DUNES BLVD.",
"city": "DAKOTA DUNES",
"state": "SD",
"zip": "57049"
}, {
"Id": 6307,
"CertificateNumber": "58548",
"Name": "1st Manatee Bank",
"FullName": "1st Manatee Bank",
"address": "12215 US HIGHWAY 301 N",
"city": "PARRISH",
"state": "FL",
"zip": "34219"
}, {
"Id": 1220,
"CertificateNumber": "6646",
"Name": "1st National Bank",
"FullName": "1st National Bank",
"address": "730 EAST MAIN STREET",
"city": "LEBANON",
"state": "OH",
"zip": "45036"
}, {
"Id": 647,
"CertificateNumber": "3564",
"Name": "1st National Bank of South Florida",
"FullName": "1st National Bank of South Florida",
"address": "1550 NORTH KROME AVENUE",
"city": "HOMESTEAD",
"state": "FL",
"zip": "33030"
}];
JQGRID code
window.makeSearchGridAjaxCall = function(detailPageUrl, SearchData, jsondata) {
console.log(" SearchData " + SearchData);
$(".search-result").jqGrid({
url: SearchData,
/**url: "/echo/json/", */
mtype: "POST",
// data: mydata,
datatype: "json",
emptyrecords: "0 records found",
postData: {
json: JSON.stringify(jsondata)
},
success: function(mydata, textStatus, jqXHR) {
console.log(" data :" + mydata);
console.log(" data :" + bmUSearchData);
},
colModel: [
{
name: 'Id',
label: ' Id',
align: 'left',
width: 20,
hidden: true
}, {
name: 'CertificateNumber',
label: 'Cert #',
align: 'center',
width: 30,
search: true,
key: true,
formatter: "showlink",
formatoptions: {
baseLinkUrl: detailPageUrl,
idName: "",
addParam: function(options) {
return "bankid=" + options.rowData.bankId + "";
}
}
},
{
name: 'address',
label: 'Address',
align: 'left',
width: 85,
search: false
}, {
name: 'city',
label: 'City',
align: 'left',
width: 50,
search: false
}, {
name: 'state',
label: 'State',
align: 'left',
width: 20,
search: true
}, {
name: 'zip',
label: 'Zip',
align: 'right',
width: 25,
search: false
},
],
additionalProperties: ["address", "city", "state", "zip"],
subGrid: true,
subGridRowExpanded: function(subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("<div class=\"col-md-1\"><b>Address: </b></div>" + item.address +
"<br/><div class=\"col-md-1\"><b>City: </b></div>" + item.city + "<br><div class=\"col-md-1\"> <b>Zip: </b></div>" + item.zip + "");
},
iconSet: "fontAwesome",
loadonce: true,
**navOptions: { reloadGridOptions: { fromServer: true } },**
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
forceClientSorting: true,
sortname: "Symbol",
height: "auto",
caption: "<b>Watch List</b>",
viewrecords: true,
autowidth: true, // set 'true' here
shrinkToFit: true, // well, it's 'true' by default
loadError: function(jqXHR, textStatus, errorThrown) {
var p = $(this).jqGrid("getGridParam"),
$errorDiv = $(this.grid.eDiv),
$errorSpan = $errorDiv.children(".ui-jqgrid-error");
$errorSpan.html("No Data Available");
$errorDiv.show();
if (p.errorDisplayTimeout) {
setTimeout(function() {
$errorSpan.empty();
$errorDiv.hide();
}, p.errorDisplayTimeout);
}
},
});
$(".search-result").jqGrid('filterToolbar', {
stringResult: true,
searchOnEnter: false,
defaultSearch: "cn"
});
$(window).resize(function() {
var outerwidth = $('#grid').width();
$('.search-result').setGridWidth(outerwidth); // setGridWidth method sets a new width to the grid dynamically
});
/************************************************************************************/
}
$(document).ready(function() {
var newURL;
var SearchData;
if (document.location.hostname == "localhost") {
newURL = "http://localhost:8080";
} else {
newURL = window.location.protocol + "//" + window.location.host;
}
console.log("URL " + newURL);
var detailPageUrl = "bm_summary_tpl.html";
//var prodUrl ="";
var mydata;
$("#basic-search").click(function(e) {
e.preventDefault();
var searchInput = $("#basicsearchVal").val()
if ($('input:text').val().length == 0) {
alert("Searched clicked and text is empty" + searchInput)
} else {
alert("go to search page " + $('input:text').val());
console.log("SearchData " + SearchData);
$(".search-result").load();
//search-result
console.log(" +searchInput " + searchInput);
SearchData = newURL + "/services-monitor/GetQuickSearch?searchString=" + searchInput;
console.log("bmSearchData " + SearchData);
makeSearchGridAjaxCall(detailPageUrl, SearchData, mydata);
$(".search-result").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
jQuery(".search-result").trigger("reloadGrid");
$("#basicsearchVal").val("");
}
});
})
;
I figured out the solution
at first i tried these 2 , which didnt work in my case.
$("#list").setGridParam({datatype:'json', page:1}).trigger('reloadGrid');
$("#list").trigger("reloadGrid", { fromServer: true, page: 1 });
I applied this which worked like a charm, it clear the grid and reload data every time the user searches new data
$(".search-result").jqGrid('GridUnload');
var searchInput = $("#basicsearchVal").val()
if ($('input:text').val().length == 0) {
alert("Please enter a Name to search")
}
else {
$( "#watchlist-b").remove();
$("#watchList-b1").remove();
$("#watchList-b2").remove();
SearchData =newURL +"/services-monitor/GetQuickSearch?searchString="+searchInput;
makeSearchGridAjaxCall (detailPageUrl,SearchData,mydata);
jQuery(".search-result").trigger("reloadGrid");
I'm not sure the best way to go about this. I want to iterate my json and find all companies that are in the US for example. This JSON might get way more complex as my app grows too, as in levels, objects, etc. I just want to know ways people are doing simple searching for filtering out subsets of data with JSON and Node.js and/or ES6 or libraries maybe such as Lodash, etc.
So for example this json, what are some ways I can search it and pull back only those companies in the USA?
[{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location":{
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
},
{
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location":{
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
},
{
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location":{
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}]
Use JavaScript native Array#filter method with ES6 arrow function
var res = data.filter(v => v.location.country === 'USA');
var data = [{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location": {
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
}, {
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location": {
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
}, {
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location": {
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}];
var res = data.filter(v => v.location.country === 'USA');
console.log(res);
You can use JavaScript's simple .filter() method to return the list of results fulfilling the filter. Say your data is in variable data
ES5
data.filter(function(item) {
return item.location.country === 'USA';
});
ES6: In ES6 you can use arrow functions for same as
data.filter((item) => {
return item.location.country === 'USA';
});
var data = [{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location":{
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
},
{
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location":{
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
},
{
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location":{
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}];
var res1 = data.filter(function(item) {
return item.location.country === 'USA';
});
const res2 = data.filter((item) => {
return item.location.country === 'USA';
});
console.log(res1);
console.log(res2);
In lodash it will be
_.filter(data, function(item) {
return item.location.country === 'USA';
});
You can use native filter function.
const items = [{
"id": 0,
"name": "Company1",
"logoUrl": "/lib/assets/company1-logo.png",
"location":{
"country": "USA",
"state": "California",
"city": "Napa"
},
"active": false
},
{
"id": 1,
"name": "Company2",
"logoUrl": "/lib/assets/company2-logo.png",
"location":{
"country": "Germany",
"state": "",
"city": "Berlin"
},
"active": false
},
{
"id": 2,
"name": "Company3",
"logoUrl": "/lib/assets/company3-logo.png",
"location":{
"country": "USA",
"state": "Michigan",
"city": "Detroit"
},
"active": false
}]
const usItems = items.filter(v => v.location.country === 'USA')