Modify JSON object using JavaScript based on title search - javascript

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);

Related

reconstruct an array of objects from another object array

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; }

Javascript to iterate through objects in array?

I'm trying to iterate through a large list of financial institutions (condensed from the 8974 objects to only 2 below) using javascript.
I want to save "id" and "name" in a new list. I'm a beginner at this and after trying some code in w3 website was unable to iterate through the different object capturing multiple "id"s and "name"s.
Anyone have an idea how to accomplish iterating through and capturing every
"id" and "name" in each json object within the json array?
{
"found": 8974,
"displaying": 8974,
"moreAvailable": false,
"createdDate": 1550566839,
"institutions": [
{
"id": 5,
"name": "Chase",
"accountTypeDescription": "Banking",
"phone": "1-800-242-7324",
"urlHomeApp": "https://www.chase.com/",
"urlLogonApp": "https://chaseonline.chase.com/chaseonline/logon/sso_logon.jsp",
"oauthEnabled": false,
"urlForgotPassword": "",
"urlOnlineRegistration": "",
"institutionClass": "banking",
"tpCurrencyCode": "USD",
"specialText": "Please enter your Chase User ID and Password. ",
"emailAddress": "https://www.bankone.com/contactus/#personal",
"address": {
"addressLine1": "270 Park Avenue",
"addressLine2": "270 Park Avenue, New York",
"city": "New York",
"country": "USA",
"postalCode": "10017",
"state": "NY"
}
},
{
"id": 170703,
"name": "WWW Bank",
"accountTypeDescription": "TestFI",
"phone": "21210",
"urlHomeApp": "http://www.finbank.com",
"urlLogonApp": "http://www.finbank.com",
"oauthEnabled": false,
"urlForgotPassword": "",
"urlOnlineRegistration": "",
"institutionClass": "testfi",
"tpCurrencyCode": "USD",
"specialText": "Please enter your WWW Bank User and Password required for login.",
"emailAddress": "finbank#finicity.com",
"address": {
"addressLine1": "Utah",
"addressLine2": "Utah",
"city": "Utah",
"country": "USA",
"postalCode": "",
"state": ""
}
}
]
}
Here we use a simnple map function to get desired array.
let data = {
"found": 8974,
"displaying": 8974,
"moreAvailable": false,
"createdDate": 1550566839,
"institutions": [
{
"id": 5,
"name": "Chase",
"accountTypeDescription": "Banking",
"phone": "1-800-242-7324",
"urlHomeApp": "https://www.chase.com/",
"urlLogonApp": "https://chaseonline.chase.com/chaseonline/logon/sso_logon.jsp",
"oauthEnabled": false,
"urlForgotPassword": "",
"urlOnlineRegistration": "",
"institutionClass": "banking",
"tpCurrencyCode": "USD",
"specialText": "Please enter your Chase User ID and Password. ",
"emailAddress": "https://www.bankone.com/contactus/#personal",
"address": {
"addressLine1": "270 Park Avenue",
"addressLine2": "270 Park Avenue, New York",
"city": "New York",
"country": "USA",
"postalCode": "10017",
"state": "NY"
}
},
{
"id": 170703,
"name": "WWW Bank",
"accountTypeDescription": "TestFI",
"phone": "21210",
"urlHomeApp": "http://www.finbank.com",
"urlLogonApp": "http://www.finbank.com",
"oauthEnabled": false,
"urlForgotPassword": "",
"urlOnlineRegistration": "",
"institutionClass": "testfi",
"tpCurrencyCode": "USD",
"specialText": "Please enter your WWW Bank User and Password required for login.",
"emailAddress": "finbank#finicity.com",
"address": {
"addressLine1": "Utah",
"addressLine2": "Utah",
"city": "Utah",
"country": "USA",
"postalCode": "",
"state": ""
}
}
]
};
let newArr = data.institutions.map(i => {
return {id: i.id, name: i.name }
});
console.log(newArr);

How to get the modified object in angularjs

I have a requirement where I need to send modified value alone in the object.
Following is my object:
{
"Code": 200,
"ErrorMessage": null,
"Result": {
"Locations": [{
"LocationName": "Location 1",
"Address": "XYZ",
"City": "Houston",
"State": "TEXAS",
"StateCode": "TX",
"Zipcode": "75201"
},
{
"LocationName": "Location 2",
"Address": "ABC",
"City": "Germantown",
"State": "CALIFORNIA",
"StateCode": "CA",
"Zipcode": "90001"
}]
}
}
I used ng-repeat inorder to display data which has input fields. Now If I modify Location 1 in that Locations Object. I want to send only Location 1 details.
Is it possible to do that in Angular. I am new to angular.
you can use ng-change to get the modified object
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.changeItem = function(item){
console.log(item.LocationName)
}
$scope.items = {
"Code": 200,
"ErrorMessage": null,
"Result": {
"Locations": [{
"LocationName": "Location 1",
"Address": "XYZ",
"City": "Houston",
"State": "TEXAS",
"StateCode": "TX",
"Zipcode": "75201"
},
{
"LocationName": "Location 2",
"Address": "ABC",
"City": "Germantown",
"State": "CALIFORNIA",
"StateCode": "CA",
"Zipcode": "90001"
}]
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="item in items.Result.Locations">
<input ng-model="item.LocationName" ng-change="changeItem(item)"/>
</div>
</div>

Filter data from object inside array typescript

I have an array events as follows,
[{
"_id": "5890b4796166c457ffdee243",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a0325"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee394"
},
"start_time": "2016-11-09T20:00:00-0600",
"id": "1644669702488073"
}, {
"_id": "5890b4796166c457ffdee242",
"description": "Please note that delivery will be delayed on all tickets until Friday January 8, 2016. Please adhere to the published ticket limits, which will be strictly enforced. If you exceed these limits, you may have any or all of your orders and tickets cancelled without notice. Please note: Every person, regardless of age, must have a ticket to be admitted to this event. RAIL RIDE EVENT: When you purchase a ticket to a Talking Stick Resort Arena event, you can ride the METRO LIGHT RAIL at no cost for four hours prior to the event through the end of the transit day.",
"name": "Adele",
"place": {
"name": "Talking Stick Resort Arena",
"location": {
"city": "Phoenix",
"country": "United States",
"latitude": 33.445995372225,
"longitude": -112.07135782626,
"state": "AZ",
"street": "201 E Jefferson St",
"zip": "85004",
"_id": "58992aebf2dbf4369c0a0327"
},
"id": "53475637527",
"_id": "5890b4856166c457ffdee427"
},
"start_time": "2016-11-21T19:30:00-0700",
"id": "905384112862937"
}, {
"_id": "5890b4796166c457ffdee24a",
"description": "Delivery of tickets will be delayed until 12/31/15",
"name": "Adele",
"place": {
"name": "AmericanAirlines Arena",
"location": {
"city": "Miami",
"country": "United States",
"latitude": 25.781236943411,
"longitude": -80.188316709574,
"state": "FL",
"street": "601 Biscayne Blvd",
"zip": "33132",
"_id": "58992aebf2dbf4369c0a0329"
},
"id": "120400119061",
"_id": "5890b4946166c457ffdee464"
},
"start_time": "2016-10-25T19:30:00-0400",
"id": "445046279020601"
}, {
"_id": "5890b4796166c457ffdee244",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a032b"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee354"
},
"start_time": "2016-11-08T20:00:00-0600",
"id": "1662607760654203"
}, {
"_id": "5890b4796166c457ffdee245",
"description": "Delivery will be delayed until Oct 2, 2016.",
"name": "Adele",
"place": {
"name": "American Airlines Center",
"location": {
"city": "Dallas",
"country": "United States",
"latitude": 32.790485550848,
"longitude": -96.810278349053,
"state": "TX",
"street": "2500 Victory Ave",
"zip": "75219",
"_id": "58992aebf2dbf4369c0a032d"
},
"id": "26606856232",
"_id": "5890b47b6166c457ffdee2e4"
},
"start_time": "2016-11-02T20:00:00-0500",
"id": "649884741817020"
}]
How to get all the city from the above json using typescript?
i have tried this,
this.eventsFiltered = this.events.filter(
book => book.place.location.city);
try this:
this.eventsFiltered = this.events.map(
book => book.place.location.city);
EDIT
i want to filter the events which has speficic places?
let events = [{
"_id": "5890b4796166c457ffdee243",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a0325"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee394"
},
"start_time": "2016-11-09T20:00:00-0600",
"id": "1644669702488073"
}, {
"_id": "5890b4796166c457ffdee242",
"description": "Please note that delivery will be delayed on all tickets until Friday January 8, 2016. Please adhere to the published ticket limits, which will be strictly enforced. If you exceed these limits, you may have any or all of your orders and tickets cancelled without notice. Please note: Every person, regardless of age, must have a ticket to be admitted to this event. RAIL RIDE EVENT: When you purchase a ticket to a Talking Stick Resort Arena event, you can ride the METRO LIGHT RAIL at no cost for four hours prior to the event through the end of the transit day.",
"name": "Adele",
"place": {
"name": "Talking Stick Resort Arena",
"location": {
"city": "Phoenix",
"country": "United States",
"latitude": 33.445995372225,
"longitude": -112.07135782626,
"state": "AZ",
"street": "201 E Jefferson St",
"zip": "85004",
"_id": "58992aebf2dbf4369c0a0327"
},
"id": "53475637527",
"_id": "5890b4856166c457ffdee427"
},
"start_time": "2016-11-21T19:30:00-0700",
"id": "905384112862937"
}, {
"_id": "5890b4796166c457ffdee24a",
"description": "Delivery of tickets will be delayed until 12/31/15",
"name": "Adele",
"place": {
"name": "AmericanAirlines Arena",
"location": {
"city": "Miami",
"country": "United States",
"latitude": 25.781236943411,
"longitude": -80.188316709574,
"state": "FL",
"street": "601 Biscayne Blvd",
"zip": "33132",
"_id": "58992aebf2dbf4369c0a0329"
},
"id": "120400119061",
"_id": "5890b4946166c457ffdee464"
},
"start_time": "2016-10-25T19:30:00-0400",
"id": "445046279020601"
}, {
"_id": "5890b4796166c457ffdee244",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a032b"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee354"
},
"start_time": "2016-11-08T20:00:00-0600",
"id": "1662607760654203"
}, {
"_id": "5890b4796166c457ffdee245",
"description": "Delivery will be delayed until Oct 2, 2016.",
"name": "Adele",
"place": {
"name": "American Airlines Center",
"location": {
"city": "Dallas",
"country": "United States",
"latitude": 32.790485550848,
"longitude": -96.810278349053,
"state": "TX",
"street": "2500 Victory Ave",
"zip": "75219",
"_id": "58992aebf2dbf4369c0a032d"
},
"id": "26606856232",
"_id": "5890b47b6166c457ffdee2e4"
},
"start_time": "2016-11-02T20:00:00-0500",
"id": "649884741817020"
}];
let eventsFiltered = events.map(
book => book.place.location.city);
console.log(eventsFiltered);
let city = 'Houston';
let eventsCt = events.filter(book => book.place.location.city == city);
console.log('2nd question');
console.log(eventsCt);
EDIT 2
i have a field named "parent" which is an array of string. i already
have a string named "12344" which is a part of array parent. how do i
check if the events.parent cotains this string and filter those
objects
let p = '1234';
let eventsF = events.filter(book => book.parent && Array.isArray(book.parent)&& book.parent.indexOf(p) !== -1);
Filter used for filter records with where conditions. In your case you want transform data and you just want a array of city from an array of object. So in this case use map instance of filter
Example
this.cityList = this.events.map(book => book.place.location.city);

Filter Records from JSON with Node or ES6

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')

Categories