Search value in JSON and return to console - javascript

I am trying to search a value in a JSON file using a input field from the user through the browser.
A sample JSON object from the array of objects looks like this:
I have an event listener to wait for click from the user. After the user clicks the function will go to the api json site and retrieve all the data.
Next I would like to search through that JSON data for what the user typed in.
Example:
user input: "Cannonball"
expected output: 196 (buy_average)
However I am unable to figure out how to search through the object array.
Here's what I got:
the parameter "data" is the JSON objects that was retrieved from API. I know that works properly because I'm able to display it in the console.
function renderHTML(data) {
var searchVal = document.getElementById("search").value;
console.log(searchVal);
for (i=0; i<data.length; i++) {
if (data["i"].name == searchVal) {
console.log(data["i"].buy_average);
}
}
};
As of right now I'm just trying to figure how to look through an object array after retrieving it from the web and display it to the console.
When I click on the button nothing in the console appears to be happening except for the user's input. How can I fix this?

Try not using i as a string - use it as an integer instead:
if (data[i].name == searchVal) {
console.log(data[i].buy_average);
}

If data is an object, the length property will give you undefined. You can get the values using Object.values() and then iterate over the properties.
let data = {
0:{ id:0,name:"aa" },
1:{ id:1,name:"Cannonball"},
2:{ id:2,name:"xx" },
};
let searchVal = "Cannonball";
Object.values(data).forEach(e=>{
if(e.name === searchVal){
console.log("This is the object: ");
console.log(e);
}
});

Related

Chrome.storage.local.set: can't set and push into array properly

I'm making a Chrome extension which has a feature to add strings from HTML form and store them in chrome storage. I want to push strings to one array, so every time I send a string from the form, it'll be added into the same array.
However, it doesn't store data correctly with my code.
document.getElementById('add-word-form').onsubmit = function(){
chrome.storage.local.get({ words:[] }, function(items) {
let newWord = document.getElementById('vocabulary').value;
let nextWord = items.words.push(newWord);
chrome.storage.local.set({ words:[nextWord] });
});
}
I'm guessing that I'm doing something wrong with chrome.storage.local.get() too, because I receive only numbers not actual string on console.log with code below...
chrome.storage.local.get({ words:[] }, function(items) {
console.log(items.words); // Array(1) // on first form submit
// [2] // on second attempt and same onwards
});
Could anyone see where I am doing wrong..?

Jquery Get array from json and see if value exists

I'm trying to write a script that retrieves data from JSON using jquery. I searched the downloaded array. How to find the value to perform any operation.
I pull out the data using getJSON and everything works. But I'm having trouble finding the search. Can anyone help me? This data from JSON:
[{"id":"10","data":"12345"},{"id":"11","data":"6666"}]
The simplest way to search through an array would be....
var data = [{"id":"10","data":"12345"},{"id":"11","data":"6666"}];
for(var row in data)
{
var item = data[row]; //This is the object {id:..., data:...}
if(item.id == ...) //Use if statement to search for data
{
//do something here when data is found
}
}

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Javascript / Parse: Follow wont return 'to' value

I am trying to get all of the users that are following the current user. From some reason Parse returns the username as undefined in the 'to' field but I am able to retrieve the user name from the 'from' field like so:
var query = new Parse.Query("Follow");
query.equalTo("to", Parse.User.current());
query.find({
success: function(users){
for (var i = 0; i < users.length; i++) {
console.log(users[i].get('from').get('username')) // returns current username
console.log(users[i].get('to').get('username')) / returns undefined
}
}
});
But those values do exist and there is a username. I am able to get the value using the fetch method but I am curious as to why this approach doesn't work. Thoughts?
From Doc, you're not getting the actual object, but the ref to that object:
Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency. ......
And
By default, when fetching an object, related Parse.Objects are not
fetched. These objects' values cannot be retrieved until they have
been fetched like so:
// Here, post is something similar to your `users[i].get('to')`
var post = fetchedComment.get("parent");
// So you need to fetch it again to get its real object.
post.fetch({
success: function(post) {
var title = post.get("title");
}
});
So what you get from users[i].get('to') is a reference to that user object. You can either fetch it again.

How to insert data, in key value pairs, into HTML

I have returned a form with some key value pairs populated. Depending on user interaction I want to insert some of them into my HTML. I have found some answers using AJAX but could not workout how to access the key value pairs via javascript. I do not want to use jquery yet as I want understand how javascript and the DOM works first. Below is an idea of what I want to do
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
while ($urls as $url) {
if (urlitem == $url->item) {
document.getElementById("urlanchor").innerHTML .= $url->urlanchor;
}
}
</script>
I know "$urls as $url" etc is PHP but I thought it was the easiest way to explain what I need to do.
I use PHP to generate the function call but I am unable to get it to display here it (pieces of code do not display)
Like so?
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
for (i in urls) {
var url = urls[i];
if (urlitem == url.item) {
document.getElementById("urlanchor").innerHTML += url.urlanchor;
}
}
</script>
urls was never defined so this code won't execute unless urls stores a bunch of url objects with those properties.
In order to create a url object that acts like the one you try to use, either use JSON to pipe it to the JavaScript or make an object:
var urls = [
{
'item': 100,
'urlanchor': 'foo'
}, {
'item': 200,
'urlanchor': 'bar'
}
];
are you asking about the setting key value pair data in a dome object then,
$('body').data('foo', 52);
link for help:-
http://api.jquery.com/data/

Categories

Resources