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; }
Related
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 am trying to access key pair values on a array object and setstate but it returns undefined
when i console.log(obj) i see the values but when i try to access them it get undefined
const data =[
[
{
"name": "chris",
"city": "unknown",
"code": "404",
"zip": "345"
},{
"name": "kulo mike",
"city": "america",
"code": "210",
"zip": "43"
}, {
"name": "chris smith",
"city": "unknown",
"code": "918",
"zip": "89"
},
]
]
i tried this
const person = data.filter(
item =>{
item.name == 'chris'
console.log(item.name)
})
and also this
const person = data.filter(
item => item.name === 'kulo mike'
)[0].zip
set state
this.state={
user: person
}
Array inside Array, try to convert your data to :
const data =[
{
"name": "chris",
"city": "unknown",
"code": "404",
"zip": "345"
},{
"name": "kulo mike",
"city": "america",
"code": "210",
"zip": "43"
}, {
"name": "chris smith",
"city": "unknown",
"code": "918",
"zip": "89"
},
]
const user = data.filter(item => item.name === 'kulo mike')[0]
setState({user})
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')
I am parsing this JSON:
[{
"cities": [
{
"city": "Pune",
"state": "Maharashtra"
},
{
"city": "Mumbai",
"state": "Maharashtra"
},
{
"city": "Panaji",
"state": "Goa"
},
{
"city": "Hyderabad",
"state": "Andhra Pradesh"
},
{
"city": "Banglore",
"state": "Karnataka"
},
{
"city": "Chennai",
"state": "Tamil Nadu"
},
{
"city": "New Delhi",
"state": "New Delhi"
}]
}]
using Dojo code:
var content = "<table border = 1><tr><th>City</th><th>State</th></tr>";
dojo.forEach(jsonData.cities, function (jsonData)
{
// Build data from the JSON
content += "<tr><td>" + jsonData.city + "</td><td>" + jsonData.state + "</td></tr>";
});
content += "</table>";
However a table with no elements is displayed! What exactly do I need to change in my Dojo code?
Try this..
var DObject = [{
"cities": [
{
"city": "Pune",
"state": "Maharashtra"
},
{
"city": "Mumbai",
"state": "Maharashtra"
},
{
"city": "Panaji",
"state": "Goa"
},
{
"city": "Hyderabad",
"state": "Andhra Pradesh"
},
{
"city": "Banglore",
"state": "Karnataka"
},
{
"city": "Chennai",
"state": "Tamil Nadu"
},
{
"city": "New Delhi",
"state": "New Delhi"
}]
}]
var output = "";
for(var i in DObject[0].cities) {
var detail = DObject[0].cities[i];
output += "<tr><td>" + detail.city + "</td><td>" + detail.state + "</td></tr>";
}
alert(output);
DEMO