This is my Json Object in simplified form.
var jsonObject =
[
{"City":"Monroe","Country":"USA","Latitude":47.8524,"Longitude":-121.98151},
{"City":"Austin","Country":"USA","Latitude":30.40137,"Longitude":-97.73542},
{"City":"Austin","Country":"USA","Latitude":30.32198,"Longitude":-97.70864}
]
I want to groupBy using City and get the count of records belonging to a specific city, The code that I've tried so far is
var query2 = $.Enumerable.From(jsonObject)
.GroupBy(
function(record) {return record.City},
function(record) {
return {City: record.City}
},
function(rec) {
return {City:rec}
}
).ToArray();
I'm still not able to get what i'm doing wrong here. i'm new to linq.js...any help would be appretiated, or atleast point me at right direction.
So you just wanted to get the count of cities? Try this instead:
var query = Enumerable.From(jsonObject)
.GroupBy(
"$.City",
null,
"{ City: $, Count: $$.Count() }") // $: Key, $$: Group
.ToArray();
//group the records
$.Enumerable.From(heatMapObjects)
.GroupBy(
"{ City: $.City }",
null,
function (key, g) {
var result = {
City:key.City
};
var groupResults = [];
g.ForEach(function (item) {
groupResults.push(item);
});
//push into array
groupedRecordsCollection.push(groupResults);
},
"$.City" // compare selector needed
)
.ToArray();
This solved my problem.
Related
This question already has answers here:
Group array of object nesting some of the keys with specific names
(2 answers)
Closed 2 years ago.
I have an array and i want to filter this array by Country and Service
i did the filter by Country but i want also do the same thing by service
this the array :
[
{
"Country":"CHINA",
"details":"None",
"Service":"BUSINESS",
},
{
"Country":"USA",
"details":"Bus-Trip",
"Service":"BUSINESS",
},
{
"Country":"USA",
"details":"Comm-Trip",
"Service":"COMMUNICATION",
},
];
I was able to do that by this code
let objectData = Data.reduce(function (acc,cur) {
if (!acc[cur.Country])
acc[cur.Country] = { data : []};
acc[cur.Country].data.push(cur)
return acc;
},
{} );
the code above allowed me to filter only by country and it's work but i want to do this same
thing by country and service BOTH and i want the result like this :
[
{
Country :"CHINA",
Service : [
{"details":"None",}
]
},
{
Country :"USA" ,
Service : [
{"details":"Bus-Trip"},
{"details":"Comm-Trip"}
]
},
]
Some slight modifications to your new object for each country so it reflects what you want and then use Object.values() to get the expected results array
let grouped = Data.reduce(function (acc,{Country, ...rest}) {
acc[Country] = acc[Country] || {Country, Services : []};
acc[Country].Services.push(rest)
return acc;
},{} );
const res = Object.values(grouped)
console.log(res)
<script>
const Data=[{Country:"CHINA",details:"None",Service:"BUSINESS"},{Country:"USA",details:"Bus-Trip",Service:"BUSINESS"},{Country:"USA",details:"Comm-Trip",Service:"COMMUNICATION"}];
</script>
You can try this code.
objectData = Data.reduce(function (acc,cur) {
if (!acc[cur.Country])
acc[cur.Country] = [];
acc[cur.Country].push({details: cur.details});
return acc;
}, {} );
objectData = Object.keys(objectData).map(key => ({
Country: key,
Service: objectData[key]
}));
You first need to modify the reduce code a bit, to contain details data only because you want to strip services.
At this moment, country will be key, so you need one more step to convert objectData to the desired format.
Object.keys(objectData) returns all countries list without duplication, so the second part finally builds the format you require.
What is the best way to filter out data that exists within an object?
I was able to do use the below code when data was just an array of values but now I need to filter out any data where the item.QID exists in my array of objects.
Data Obj:
var data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob
}]
Snippet:
// I don't want to include data if this QID is in my object
this.employees = emp.filter(item =>!this.data.includes(item.QID));
From what I understand, includes only works on an array so I need to treat all of the QID values in my object as an array.
Desired Outcome: (assuming item.QID = ABC123)
this.employees = emp.filter(item =>!this.data.includes('ABC123'));
Result:
var data = [{
QID: 'DEF456',
Name: 'Bob'
}]
UPDATE:
Apologies, I left some things a little unclear trying to only include the necessary stuff.
// People Search
this.peopleSearchSub = this.typeahead
.distinctUntilChanged()
.debounceTime(200)
.switchMap(term => this._mapsService.loadEmployees(term))
.subscribe(emp => {
// Exclude all of the current owners
this.employees = emp.filter((item) => item.QID !== this.data.QID);
}, (err) => {
this.employees = [];
});
The above code is what I am working with. data is an object of users I want to exclude from my type-ahead results by filtering them out.
The question is a little ambiguous, but my understanding (correct me if I'm wrong), is that you want to remove all items from a list emp that have the same QID as any item in another list data?
If that's the case, try:
this.employees = emp.filter(item => !this.data.some(d => d.QID === item.QID))
some is an array method that returns true if it's callback is true for any of the arrays elements. So in this case, some(d => d.QID === item.QID) would be true if ANY of the elements of the list data have the same QID as item.
Try Object#hasOwnProperty()
this.employees = emp.filter(item =>item.hasOwnProperty('QID'));
You can use a for ... in to loop through and filter out what you want:
const data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob'
}]
let newData = [];
let filterValue = 'ABC123';
for (let value in data) {
if (data[value].QID !== filterValue) {
newData.push(data[value]);
}
}
newData will be your new filtered array in this case
You can use an es6 .filter for that. I also added a couple of elements showing the filtered list and an input to allow changing of the filtered value. This list will update on the click of the button.
const data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob'
}]
displayData(data);
function displayData(arr) {
let str = '';
document.getElementById('filterList').innerHTML = '';
arr.forEach((i) => { str += "<li>" + i.QID + ": " + i.Name + "</li>"})
document.getElementById('filterList').innerHTML = str;
}
function filterData() {
let filterValue = document.getElementById('filterInput').value;
filterText (filterValue);
}
function filterText (filterValue) {
let newArr = data.filter((n) => n.QID !== filterValue);
displayData(newArr)
}
<input id="filterInput" type="text" value="ABC123" />
<button type ="button" onclick="filterData()">Filter</button>
<hr/>
<ul id="filterList"><ul>
I have the following object structure:
var mapData =
{
Summary:
{
ReportName: 'Month End Report'
},
NortheastRegion:
{
Property1: 123,
RegionName: 'Northeast'
},
SoutheastRegion:
{
Property1: 456,
RegionName: 'Southeast'
},
}
I want to write a grep function that returns an array of region names. The following function is not returning any values:
var regions = $.grep(mapData, function(n,i)
{
return n.RegionName;
});
What am I missing here?
$.grep is for filtering arrays. Your structure isn't an array. $.grep is also just for filtering, but you're talking about both filtering (leaving out Summary) and mapping (getting just the region names).
Instead, you can use
Object.keys and push:
var regions = [];
Object.keys(mapData).forEach(function(key) {
var entry = mapData[key];
if (entry && entry.RegionName) {
regions.push(entry.RegionName);
}
});
Object.keys, filter, and map:
var regions = Object.keys(mapData)
.filter(function(key) {
return !!mapData[key].RegionName;
})
.map(function(key) {
return mapData[key].RegionName;
});
A for-in loop and push:
var regions = [];
for (var key in mapData) {
if (mapData.hasOwnProperty(key)) {
var entry = mapData[key];
if (entry && entry.RegionName) {
regions.push(entry.RegionName);
}
}
}
...probably others.
That's an object, not an array. According to the jQuery docs, your above example would work if mapData were an array.
You can use lodash's mapValues for this type of thing:
var regions = _.mapValues(mapData, function(o) {
return o.RegionName;
});
ES6:
const regions = _.mapValues(mapData, o => o.RegionName)
As stated in jQuery.grep() docs, you should pass an array as data to be searched, but mapData is an object. However, you can loop through the object keys with Object.keys(), but AFAIK you'll have to use function specific for your case, like:
var mapData =
{
Summary:
{
ReportName: 'Month End Report'
},
NortheastRegion:
{
Property1: 123,
RegionName: 'Northeast'
},
SoutheastRegion:
{
Property1: 456,
RegionName: 'Southeast'
},
};
var keys = Object.keys(mapData),
result = [];
console.log(keys);
keys.forEach(function(key) {
var region = mapData[key].RegionName;
if (region && result.indexOf(region) == -1) {
result.push(region);
}
});
console.log(result);
// Short version - based on #KooiInc answer
console.log(
Object.keys(mapData).map(m => mapData[m].RegionName).filter(m => m)
);
$.grep is used for arrays. mapData is an object. You could try using map/filter for the keys of mapData, something like:
var mapData =
{
Summary:
{
ReportName: 'Month End Report'
},
NortheastRegion:
{
Property1: 123,
RegionName: 'Northeast'
},
SoutheastRegion:
{
Property1: 456,
RegionName: 'Southeast'
},
};
var regionNames = Object.keys(mapData)
.map( function (key) { return mapData[key].RegionName; } )
.filter( function (name) { return name; } );
console.dir(regionNames);
// es2105
var regionNames2 = Object.keys(mapData)
.map( key => mapData[key].RegionName )
.filter( name => name );
console.dir(regionNames2);
Just turn $.grep to $.map and you would good to go.
var regions = $.map(mapData, function(n,i)
{
return n.RegionName;
});
I have a JSON data. I am pushing this data to another array. The problem i am facing is, i want to filter array whose data attrs has src property. And push these array to another array. Can anyone will help me in this.I am not getting a way to do this.
My Json data is like:
DATA:
[
{
"data":{
},
"type":"image",
"attrs":{
"x":92,
"y":163,
"width":100,
"height":100,
"src":"http://localhost:63342/wodrobs/app/scripts/views/img/top.jpg",
"cursor":"move",
"opacity":1
},
"transform":"",
"id":0
},
{
"data":{
},
"type":"path",
"attrs":{
"fill":"none",
"stroke":"#000",
"stroke-dasharray":"- ",
"opacity":0.5
},
"transform":"",
"id":17
},
]
As far as I understood from your pseudo-json, you can do like this:
//your data
var a = [
{'src':"a.src"},
{'id':"someid"},
{'src':"b.src"}
];
//the result array
var result = [];
for(i=0; i<a.length;i++){
var e = a[i];
if(e.src){
result.push(e);
}
}
console.log(result);
http://jsbin.com/hujicopuca/1/edit?html,js,console,output
I think this is what you are looking for:
function HasSrcProperty(value, index, ar) {
return value.some(elem => elem.indexOf("src") > -1)
}
var result = yourJsonArray.filter(HasSrcProperty);
For more info on javascript array filter and some:
https://msdn.microsoft.com/en-us/library/ie/ff679973%28v=vs.94%29.aspx
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Got the answer. i was doing silly mistake.
var filterData= _.filter(jsonData, function (data) {
return data.attrs.src;
});
I have an external file people.json. How I can convert it to a javascript array with json syntax?
this is the people.json content:
{
"1":{
"Name":"Jhon",
"Surname":"Kenneth",
"mobile":329129293,
"email":"jhon#gmail.com"
},
"2":{
"Name":"Thor",
"Surname":"zvalk",
"mobile":349229293,
"email":"thor#gmail.com"
},
"3":{
"Name":"Mila",
"Surname":"Kvuls",
"mobile":329121293,
"email":"mila#gmail.com"
}
}
I want an array with this format
var person = [
{ "name":"jhon" , "surname":"kenneth", "mobile":329129293, "email":"jhon#gmail.com"},
{ "Name":"Thor", "Surname":"zvalk", "mobile":349229293, "email":"thor#gmail.com" },
{ "Name":"Mila", "Surname":"Kvuls", "mobile":329121293, "email":"mila#gmail.com"}
];
I tried with the next code, but it doesnt worker:
var person;
$.getJSON('people.json', function (json) {
person[]= json
});
By the way, the file contacts.json is in my server.
Can use jQuery $.map()
var newArray=$.map( originalObject, function(item){
return item;
})
DEMO: http://jsfiddle.net/qmfn2/
Try like this:
$.getJSON('people.json', function (json) {
var people = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
people.push({
name: item.Name,
surname: item.Surname,
mobile: item.mobile,
email: item.email
});
}
}
// at this stage the people object will contain the desired output
});
First you will need to fetch the JSON file using an AJAX request. Then iterate through the received JSON object and add each property to an array.
function convertToArray (receivedObj) {
var array = [], key;
for (key in receivedObj) {
array.push(receivedObj[key]);
}
return array;
}
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});
Hope this helps!
Like this:
var array = $.map($.parseJSON(data), Object);
http://jsfiddle.net/mXFKL/
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});