Jquery Get array from json and see if value exists - javascript

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
}
}

Related

vuejs make array of objects data

I have array of data (selected items) and I need to extract ids of this array into new array so I can send those ids only to back-end.
Code
method
toggleSelection(rows) {
console.log('this.multipleSelection : ',this.multipleSelection); // prints my default array (include all data)
this.multipleSelection.forEach(row => {
console.log('rows: ', row) // get each object of array (extract ids here)
// send axios request to backend (ids only)
});
},
Screenshot
here is result of console codes above
any idea?
At first I need to say I never worked with Vue.js. But in simple vanilla-javascript you could use the map function. I don't know if this works but Here is a possible answer:
yourids = this.multipleSelection.map(row => row.id);

Search value in JSON and return to console

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

AngularJS: Discard duplicates element from an Json data which is from nodejs server sides rendered data

I am using "itunes-search" module in nodejs and it is send the sends the search results as Json data. The Json data has a filed named "artistName" which has duplicates element I can see. but I want to print the "artistName" values discarding the duplicates instance. Means one value should be printed only one time. I have only included the
<script type="text/javascript" src="/angular.js"></script>
<script src="js/angular-file-upload.min.js"></script>
I am trying with the bellowed code. But it is not working. Multiple elements of value are also printed.
<ul>
<li data-ng-repeat="data in response | orderBy:'artistName' | unique:'artistName' ">
<b> {{data.artistName}} <b><br/>
</li>
</ul>
I will really appreciate him who will help me.
You'll need to create your filter. Here is an example :
angular.module('app',[]).filter('unique', function() {
return function(list, attribute) {
var result= [];
var keys = [];
// Find duplicates
angular.forEach(list, function(item) {
if(keys.indexOf(item[attribute]) === -1) { // Not already present
keys.push(item[attribute]);
result.push(item);
}
});
return result;
};
The error says you need to have unique filter loaded in your angular app in order to use it. Angular could not find the filter and hence throwing the error.
Here is the way you can fix that.
Save this as unique.js in your scripts and load it in HTML.
Add 'ui.filters' to your dependencies in your app.

append data to a JS "JSON array"

In JS (it is node/js but actually is a general JS question)
I have a data object which is a result of JSON coming from the server.
I want to manipulate the data before passing it to the view.
How can I do that? (I can make additional objects that contain the rest of the data but it feels wrong and un-natural)
var response = JSON.parse(moment_respose_content );
if (response.success)
{
var data = response.data[0];
//add additional fields to data
}
This may have already been answered
A JSON object is just a JS object, you can add/edit/remove parts like you would any other.

JQuery Autocomplete GET & JSON array data security concerns

I am learning JQuery with a MVC3 book. I find that Json data is really easy to use, but it may not be safe.
Consider the scenario, say, I got a CRM with senstive customer infomation. Ajax returns Json array as search results. The search textbox ajax autocomplete also return Json array of senstive keywords from database. etc...They all use GET method.
However, it is said that GET method has vulnerabilities when passing around Json array data:
http://haacked.com/archive/2009/06/25/json-hijacking.aspx
http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
How do you JQuery experts out there go about fixing this issue? Please help.
--- EDIT: ---
#Gren. Awesome. Thank you. Based on your tips, here is what I figured out.
The normal autocomplete returning json array
and a mod one with a json object wrapping the array
Here is the code, assuming we got a global List named txtlst in the controller.cs...
// normal one
public JsonResult AutoCompleteHelper1(string term) {
//if (!Request.IsAjaxRequest()) return null;
var lst = txtlst.Where(s => s.StartsWith(term)).ToList();
var res = lst.Select(x => new { value = x }).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
//mod one
public JsonResult AutoCompleteHelper2(string term) {
//if (!Request.IsAjaxRequest()) return null;
var lst = txtlst.Where(s => s.StartsWith(term)).ToList();
var res = lst.Select(x => new { value = x }).ToList();
return Json(new { wrapper= res, name="wrapper" }, JsonRequestBehavior.AllowGet);
}
}
and then in the .cshtml file...
<p>Auto Complete Example</p>
<input type="text" name="q" id="MyInput1" data-autocomplete-source="#Url.Action("AutoCompleteHelper1", "Home")"/>
<input type="text" name="q" id="MyInput2" data-autocomplete-source="#Url.Action("AutoCompleteHelper2", "Home")" />
and then in the .js file...
$(document).ready(function () {
// normal autocomplete
$("#MyInput1").autocomplete({ source: $("#MyInput1").attr("data-autocomplete-source") });
// mod autocomplete with a wrap
$("#MyInput2").autocomplete({
source: function (req, add) {
$.getJSON($("#MyInput2").attr("data-autocomplete-source"), req, function (data) {
var suggestions = [];
$.each(data.wrapper, function (i, o) {
suggestions.push(o.value);
});
add(suggestions);
});
}
});
});
--- EDIT 2: ---
Please ignore those comments that are telling me to use POST. They
are not reading the blog links or do not understand the issue.
The other option is to wrap your JSON Arrays within JSON objects. The article and comments in it answered this question.
Edit:
From the article:
The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file.
If you wrap your json array in an object {"myJsonArray":[{"name":"sensitive"},{"name":"data"}]} the HTML script tag would not be able to execute.
Security of an Ajax/JSONP/JSON call is the same exact thing as the security of an http call since Ajax requests are http requests. Nothing changes in how you handle it. You make sure the user is logged in and can access the information.
If you are worried about data being cached, use Post or set the proper no caching headers with the backend.
EDIT:
Things you can do to prevent JOSN from being read is the infinite loop trick. Stick an infinte loop in front of the call, means your Ajax call will have to strip this before using it.
You can use keys, third party site would not have the keys needed to validate the request.
You can check referrers.

Categories

Resources