Making a search in json file by query - javascript

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

Related

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.

Find a key in Dictionary and access its value containing a KeyValue pair of Strings

I've got a dictionary of <long, List<KeyValuePair<string,string>> which I'm trying to access in JavaScript.
var data = new Dictionary<long, List<KeyValuePair<string, string>>>();
e.g: data would have Key:100, Value: Name, John
In Javascript,
I need to get all KeyValuePair<string,string>in data and add it into mu.Mappings using the long key.
ViewModel.Degrees.forEach(function(mu) {
mu.Mappings = ViewModel.MappingListResults.Keys(mu.ID)
.find((value => ViewModel.MappingListResults[key] === mu.ID)); //doesn't work
});
Any ideas or suggestions?

Why can't I use filter for nested objects in javascript?

I am preparing a weather app that gives suggestion list as we enter an input city name.
Json file is in this format:
{"coord":{"lon":-0.13,"lat":51.51},
"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],
"base":"stations",
"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},
"visibility":10000,
"wind":{"speed":4.1,"deg":80},
"clouds":{"all":90},"dt":1485789600,
"sys":{"type":1,"id":5091,"message":0.0103,
"country":"GB",
"sunrise":1485762037,
"sunset":1485794875},
"id":2643743,
"name":"London",
"cod":200}
So my code for that functionality is:
inputcity.addEventListener("input",()=>getweather(inputcity.value));
const getweather=async searchtext=>{
const res=await fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputcity.value+"&units=metric&appid=78a661b7c335021c7d85065aea3673be");
const cities= await res.json();
let matches=cities.filter(city=>{
const regex=new RegExp(`^${searchtext}`,'gi');
return city.name.match(regex);
});
console.log(matches);
};
What I want is to show a list of city names starting with same letters.
But it's showing error the following error:
*Uncaught (in promise)TypeError: cities.filter is not a function*
because this api gives data in nested objects not in array of objects.
How can get my code working using filter or any method?
Because i don't have 50 reputation to leave a comment on the comment section.
I will just leave my comments here, so you can got an idea how to do it.
Your code that fetch the API's from https://api.openweathermap.org/data/2.5/weather?q="+inputcity.value+"&units=metric&appid=78a661b7c335021c7d85065aea3673be is only returning data for 1 city.
The returned data is also not a ARRAY, It's a JSON object.
See here for better viewing of your data : https://codebeautify.org/jsonviewer/cb13b4bd
For your idea about suggestion list on city name when users inputted the data, is not on their api's feature.
You should make a array for the city name lookup and shows the suggestion with .startsWith(user.input).
Example super inefficient code to do that :
const userinput = "a";
var city = ["aaa", "abc", "bca", "cba", , "ccc"];
city.forEach(searchsuggestion);
function searchsuggestion(value, index) {
if (value.startsWith(userinput)) {
console.log("Suggestion : " + value);
}
else {
return;
}
}
Your Console output for the above code should be :
Suggestion : aaa
Suggestion : abc

delete user from json table in js

So I'm a beginner to js and I have a table of users in a json file and I'm making an account delete feature. I have a find set up to find the user and it works fine but I can't figure out how to make it delete the user from the file, any help would be appreciated!
Json:
{
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
JS:
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
EDIT: Not sure if it's an array or a table I don't know a lot about json
You need to use:
Array#find to find a given user by some given criteria.
Array#indexOf to get the index of the found user in users
Array#splice to drop one element starting from the index given by Array#indexOf:
const input = {
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == '780748c5d4504446bbba3114ce48f6e9'
&& discordId == '471621420162744342',
input.users
)
// Output: 0 <-- User has been removed!
console.log(input.users.length)
About persisting the change, it's just about calling JSON.stringify (input) and then just write the contents to the desired output file. See this other Q&A: Writing files in Node.js
With great help from Cat and Matias I came up with this code that works!
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
const input = arrayOfObjects;
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == findEntry.Id
&& discordId == findEntry.discordId,
input.users
)
console.log('unlinked')
fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
Here's a quick tutorial for you:
"Users" would be either an array (using []) or a javascript object (using {}), your choice. There won't be any actual tables unless you use a database instead of a JSON file (although if your JSON expression is as simple as your example, you could almost think of it as a table.) -- And actually, a third option would be to use the javascript Map type, which is like a beefed-up object, but I won't address that here.
While using an array would make it a bit easier to retrieve a list of data for all users (because arrays are simpler to iterate through), using an object would make it considerably easier to retrieve data for a single user (since you can directly specify the user you want by its key instead of needing to loop through the whole array until you find the one you want.) I'll show you an example that uses an object.
The individual user in your sample code is an example of a javascript object. JSON lets you convert an object to a string (for storage, I/O, and human readability) and back to an object (so javascript can understand it). You use the JSON.stringify() and JSON.parse() methods, respectively for these conversions. The string has to be JSON-formatted or this won't work, and your example is almost in JSON format.
To comply with JSON formatting, you could structure a Users object as follows. (Of course we're looking at the stringified version because mere humans can't easily read an "actual" javascript object):
"Users": { // Each individual user is a property of your users object
"780748c5d4504446bbba3114ce48f6e9": // The Id is the key in the "key/value pair"
{ // The individual user object itself is the value in the key/value pair
// Id is duplicated inside user for convenience (not necessarily the best way to do it)
"id": "780748c5d4504446bbba3114ce48f6e9",
"name": "ImBattleDash", // Each property of the user is also a key/value pair
"discordId": "471621420162744342", //Commas separate the properties of an object
"dateAdded": "1548295371" // All property values need double quotes for JSON compatibility
}, // Commas separate the properties (ie the individual users) of the users object
"446bbba3114ce48f6e9780748c5d4504": // This string is the second user's key
{ // This object is the second user's value
"id": "446bbba3114ce48f6e9780748c5d4504",
"name": "Wigwam",
"discordId": "162744342471621420",
"dateAdded": "1548295999"
}
}
Once you retrieve the string from storage, you convert it to an object and delete a user as follows. (This is broken down into more steps than necessary for clarity.):
let usersObject = JSON.parse(stringRetrievedFromFile);
let userId = "780748c5d4504446bbba3114ce48f6e9";
let userToModifyOrDelete = usersObject[userId];
delete userToModifyOrDelete;
To change the user's discordId instead, you would do:
let discordId = userToModifyOrDelete.discordId; // Not necessary, just shows how to retrieve value
let newDiscordId = "whateverId";
userToModifyOrDelete.discordId = newDiscordId;
And you'd convert the object back into a string to store in your file with:
JSON.stringify(usersObject);
Hopefully that's almost all you need to know about JSON!

How to get result from json object with angular js?

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".

Categories

Resources