How to get result from json object with angular js? - javascript

I have a json file and want to count the rows by specific value and load to my page using angular js models.
The json is look like this:
[
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
]
The json file loaded by $http service.
How can I run such query on the json data:
select COUNT(`name`) as a from tbl_ben where ` gender` = 'Female' and `district` = 'LA';
any idea? 
 

You can't run SQL queries on JSON out-of-the-box, so let's work through it in JavaScript.
We have some data in an array, let's call it people:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
Now, let's filter it down based on their gender and district like in your query:
let filtered = people.filter(p => (p.district === "LA") && (p.gender === "Female"));
Now instead of using COUNT, we can just check the length property of our filtered array:
let count = filtered.length;
We can abstract this code away into a nice function which will do the work for us:
let getCount = (array, predicate) => {
return array.filter(predicate).length;
};
And we can then use this function like so:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
getCount(people, p => p.district === "NY" && p.gender === "Male"); // 1
Note that based on your example data, the count is 0 as you have nobody in the district "LA".

Related

Array of object - get id for selected user name inside function

const user = [
{name:"jonh" ,id:EAD1234},
{name:"peter" ,id:EAD1235},
{name:"matt" ,id:EAD1236},
{name:"henry" ,id:EAD1237},
]
I have above mentioned array of object,
I want to get selected user id dynamically based on user selection using es6 and javascript e.g. if i select john i should get EAD1234. and it must suitable on large number of records
I tried using filter method
No need to filter through the whole array if the id values are unique:
function getUserByID(id, users) {
for (const u of users) {
if (u.id === id) {
return u;
}
}
return null;
}
If your data really is exceptionally large and it makes sense to store it on the front-end look into using IndexedDB.
Edit: Someone in the comments somewhere mentioned Array.prototype.find(), so you might as well just use the built-in.
function getUserByID(id, users) {
return users.find((u) => u.id === id) || null;
}
If the data is samll,then just combine Array.filter() and Array.map() can do it.
If the data is too large,we can store the data into a database such as mysql or redis,then query it dynamiclly
const user = [
{name:"jonh" ,id:'EAD1234'},
{name:"peter" ,id:'EAD1235'},
{name:"matt" ,id:'EAD1236'},
{name:"henry" ,id:'EAD1237'}
]
let id = 'EAD1234'
let result = user.filter(u => u.id === id).map(u => u.name)
console.log(result)
const user = [
{name:"john" ,id:'EAD1234'},
{name:"peter" ,id:'EAD1235'},
{name:"matt" ,id:'EAD1236'},
{name:"henry" ,id:'EAD1237'},
];
let userName = "john";
let userId = user.filter(user => user.name === userName)[0].name;

Making a search in json file by query

i want to make a search in a json file by query
Example:
My json file:
[{
"Id":1,
"name":"test"
},
{
"Id":2,
"name":"test"
}]
And if i search {"name":"test"} i get the full objects whos name is test
ADD: I misspoke its the user who enter the query how can i get the key and the value from the query {key:value} and the user can entre multiple keys and values (like the search in atlas mongodb)
UP!!
As per your question you are using JSON inside of an array.
So you can simply filter the array to find JSON which contains name="test"
Follow the below step:
let userArray = [{"Id":1,"name":"test"},{"Id":2,"name":"test"}]
const filteredUser = userArray.filter((user) => user.name === "test")
Try something simple:
var myjson ='[{"Id":1,"name":"test"},{"Id":2,"name":"test"},{"Id":3,"name":"nottest"}]';
var slag = JSON.parse(myjson).filter(doc => doc.name === 'test');
console.log(slag);

JavaScript array of huge data (500K record) taking time to search and add

My function is called in loop which returns more than 500k record.
I have to insert that record in a JavaScript array. Before inserting records to array need to check existing array has duplicate records or not. If the record is duplicate then exclude the record.
When array size increases the run time of the function is very high. Please suggest me a way to optimize search.
function AddDataToArray(StdName, currObjectSTD, bufferObject, attributes, bufferSTD) {
var result = false;
var existingObjects = AllDataArray.find(item => {
item.OBJECTID==attributes.OBJECTID
&& item.name == bufferObject.name
&& item.StdName == StdName);
});
if (existingObjects.length == 0) {
var currentObject = {
"ID": 0,
"currObjectSTD": currObjectSTD,
"color": bufferObject.color,
"name": bufferObject.name,
"attributes": attributes,
"StdName": StdName,
"objectID": objectID,
"bufferSTD": bufferSTD,
"shape": null,
"shapeSTD": null
};
AllDataArray.push(currentObject);
result = true;
}
return result;
}
As a speedup workaround I suggest you coming up with some kind of hash map based on your array to avoid continuos looping through array
const dataHashMap = _(AllDataArray)
.keyBy(item => `${item.OBJECTID}-${item.name}-${item.StdName}`)
.mapValues(() => true)
.value();
var existingObjects = dataHashMap[`${attributes.OBJECTID}-${bufferObject.name}-${StdName}`]
or alternative solution
let groupedDataHashMap = {}
AllDataArray.forEach(item => {
_.set(
groupedDataHashMap,
[
item.OBJECTID,
item.name,
item.StdName
],
true
)
})
var existingObjects = _.get(
groupedDataHashMap,
[
attributes.OBJECTID,
bufferObject.name,
StdName
],
false
)
I used lodash methods but if you prefer using native array/object methods you can come up with your own implementation, but the idea is the same
P.S you need to create this hash map once you fetched your array and populate it with new items simultaneously with your array to keep it up-to-date with your array

Retrive alle values as array on key in firebase for react native

Hey i have a list of calendar evnets where the key is by date but i would like u get out all values as a array of data
but i wish to get the data out kinda like this but ofc with the rest of the values i have
'2012-05-25': [{date: '2021-04-10', name: "",},{date: '2021-04-10', name: "",}]
is there any way using firebase query to get it out in the format over ?
Something like this should do the trick:
cons ref = firebase.database.ref("calendar/events");
ref.once("value").then((snapshot) => {
let result = {};
snapshot.forEach((daySnapshot) => {
result[daySnapshot.key] = [];
daySnapshot.forEach((eventSnapshot) => {
result[daySnapshot.key].push(eventSnapshot.val());
})
})
console.log(result);
});
So we load all data from the database and then use two nested forEach loops to handle the dynamic levels underneath, and result[daySnapshot.key] to get the date key.

Javascript ForEach on Array of Arrays

I am looping through a collection of blog posts to firstly push the username and ID of the blog author to a new array of arrays, and then secondly, count the number of blogs from each author. The code below achieves this; however, in the new array, the username and author ID are no longer separate items in the array, but seem to be concatenated into a single string. I need to retain them as separate items as I need to use both separately; how can I amend the result to achieve this?
var countAuthors = [];
blogAuthors = await Blog.find().populate('authors');
blogAuthors.forEach(function(blogAuthor){
countAuthors.push([blogAuthor.author.username, blogAuthor.author.id]);
})
console.log(countAuthors);
// Outputs as separate array items, as expected:
// [ 'author1', 5d7eed028c298b424b3fb5f1 ],
// [ 'author2', 5dd8aa254d74b30017dbfdd3 ],
var result = {};
countAuthors.forEach(function(x) {
result[x] = (result[x] || 0) + 1;
});
console.log(result);
// Username and author ID become a single string and cannot be accessed as separate array items
// 'author1,5d7eed028c298b424b3fb5f1': 15,
// 'author2,5dd8aa254d74b30017dbfdd3': 2,
Update:
Maybe I can explain a bit further WHY on what to do this. What I am aiming for is a table which displays the blog author's name alongside the number of blogs they have written. However, I also want the author name to link to their profile page, which requires the blogAuthor.author.id to do so. Hence, I need to still be able to access the author username and ID separately after executing the count. Thanks
You could use String.split().
For example:
let result = 'author1,5d7eed028c298b424b3fb5f1'.split(',')
would set result to:
['author1' , '5d7eed028c298b424b3fb5f1']
You can then access them individually like:
result[1] //'5d7eed028c298b424b3fb5f1'
Your issue is that you weren't splitting the x up in the foreach callback, and so the whole array was being converted to a string and being used as the key when inserting into the results object.
You can use array destructuring to split the author name and blog id, and use them to optionally adding a new entry to the result object, and then update that result.
countAuthors = [
['author1', 'bookId1'],
['author2', 'bookId2'],
['author1', 'bookId3'],
['author1', 'bookId4'],
['author2', 'bookId5']
]
var result = {};
countAuthors.forEach(([author, id]) => {
if (result[author] === undefined) {
result[author] = {count: 0, blogIds: []};
}
result[author].count += 1;
result[author].blogIds.push(id);
});
console.log(result);

Categories

Resources