I stored an object in one variable (Consider as datatable).
var data=[{"controlID":"A","currentValue":"10","onChange":"","onClick":""},
{"controlID":"B","currentValue":"5","onChange":"Testing(A,B)","onClick":""},
{"controlID":"C","currentValue":"-5","onChange":"Testing1(A,B)","onClick":""},
{"controlID":"D","currentValue":"","onChange":"Testing2(B,C)","onClick":""},{"controlID":"E","currentValue":"","onChange":"Testing3(C,D)","onClick":""},{"controlID":"F","currentValue":"","onChange":"","onClick":""}];
Now I know the second row key value as B. How to I Get the Third row (i.e., "C" row values)
Am new of this field. Please help us to helpful.
This function will return your index:
var FindIndexOfControlID = function(id, data){
for(var i = 0; i < data.length ; i++){
if( data[i]['controlID'] == id ){
return i;
}
}
};
Usage:
var index = FindIndexOfControlID('C', data);
Live Example
http://jsfiddle.net/urahara/medhgm7b/
NOTE
Alternatively you may also want to implement function that returns index of any specified property and value:
var FindIndexOfProperty = function(value, property, data){
for(var i = 0; i < data.length ; i++){
if( data[i][property] == value ){
return i;
}
}
};
Usage
FindIndexOfProperty('-5', 'currentValue',data); // returns 2
You can return the third row in javascript by simply executing var thirdRow = data[2]. The row will be returned as an object.
Related
Hello I am working in a project to keep learning js wich is in this URL: http://themapapp.herokuapp.com/ and this is the github page: https://github.com/xtatanx/mapApp
In some of the parts of my code I need to check if some property already exists in an array of objects and also I that property value is equal to something, so far the code that I am using to to dis is this one:
// check if property value exist in an array of objects
function searchByValue(value, property, array){
for(var i = 0; i < array.length; i++){
if(array[i][property] === value){
return true;
}
}
return false;
}
And I use it like this:
if(searchByValue('myDestiny', 'id', map.markers)){
map.markers[1].setPosition({
lat: results[0].geometry.location.k,
lng: results[0].geometry.location.A
});
}else{
createMarker(results[0].geometry.location.k, results[0].geometry.location.A, 'myDestiny');
My question is if actually I am doing it the way it is or if I am wrong because I sometime think that the function its not returning the correct value or is not working good, I will appreciate if some of you guys could give me some advice in how to achieve this, or improve it.
EDIT
i finished with something like
Array.prototype.searchBy = function(property, value){
var _property = arguments[0];
var _value = arguments[1];
if(arguments.length === 1){
return Array.prototype.indexOf.apply(this, arguments);
}
for(var i = 0; i < this.length; i++){
if(this[i][_property] === _value ){
return true;
}
}
return false;
};
Didnt used the checkprop part because actually doesnt understood how it works o_O. thank you very much to #GameAlchemist and #jshanley
Your code works well as long as every object in the array you are searching has defined the property you check for. I could see running into a problem otherwise. You might try adding a check that the property is defined before trying to access its value, like this:
function searchByValue(value, property, array){
for(var i = 0; i < array.length; i++){
// check that property is defined first
if(typeof array[i][property] !== 'undefined') {
// then check its value
if(array[i][property] === value){
return true;
}
}
}
return false;
}
I would rather define this function as a method of Array, and why not overload indexOf, that would act as std indexOf with one argument, and as indexOf(value, propertyName, checkProp) with three arguments.
var __oldIndexOf = Array.prototype.indexOf ;
Array.prototype.indexOf = function() {
if (arguments.length==1) return __oldIndexOf.apply(this, arguments);
var value = arguments[0];
var property = arguments[1];
var checkProp = arguments[2];
if (!checkProp) {
for(var i = 0; i < this.length; i++){
if(this[i][property] === value){
return i;
}
} else {
for(var i = 0; i < this.length; i++){
var thisItem = this[i] ;
if (!Object.hasOwnProperty(thisItem, property))
throw('indexOf error : object ' + thisItem + ' has no property ' + property);
if(this[i][property] === value){
return i;
}
}
return -1;
};
so, for your code,
if (searchByValue('myDestiny', 'id', map.markers)) { ...
becomes :
if (map.markers.indexOf('myDestiny', 'id') != -1 ) { ...
and obviously you can store the found index in case you need it.
i think that, in your case, what you meant was rather using the found index :
var destinyIndex = map.markers.indexOf('myDestiny', 'id');
if(destinyIndex != -1){
map.markers[ destinyIndex ].setPosition({
lat: results[0].geometry.location.k,
lng: results[0].geometry.location.A
});
} else {
createMarker(results[0].geometry.location.k, results[0].geometry.location.A,
'myDestiny');
}
Edit : idea of checking that property exists is courtesy of #jshanley
Using the following function, I am searching an array for the existence of a value;
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ["large-car"];
function searchArray(arguments)
{
var o = {};
for(var i=0;i<arguments.length;i++)
{
o[arguments[i]]=null;
}
return o;
}
if (carType in searchArray(checkboxValues) )
//do something...
This condition works well when carType (which is an array itself) contains only one value but when carType contains multiple values such as,
var carType = ["large-car", "4WD"];
...then the function will return false.
To give some background, what I am trying to do is show or hide map markers (via Google Maps) based on certain conditions,
Automatic
Manual
Small Car
Large Car
4WD
Each of these values is represented as a checkbox. If "Automatic" and "Small Car" are selected, then only shown map markers who contain both those values.
If "Automatic", "Small Car" and "Large Car" are selected then only show values which match those selections.
This works if the carType array contains only a single value but as an individual vehicle may have more than one type as shown above, this is where the function fails.
What's the best way to write the function to allow for comparing multiple values in one array against that of another?
Snippet taken from this answer.
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
And then use it like this:
var checkboxValues = ['large-car', 'small-car', 'automatic'],
carType = ["large-car"],
merged = arrayUnique(checkboxValues.concat(carType));
if (merged.length === checkboxValues.length) {...}
If you need to return the matching elements of two arrays you can do this:
function matchArrays(base, toSearch) {
var returnArray = [];
for (var i = 0; i < toSearch.length; i++) {
if (base.indexOf(toSearch[i]) !== -1) returnArray.push(toSearch[i]);
}
return returnArray;
}
Usage:
var match = matchArrays(checkboxValues, carType); // return "large-car"
Take a look at array_intersect from PHPJS, a reproduction of PHP's array_intersect function in JavaScript.
You can use js functionality to match array.
One ways is to use indexOf() function that return the index of the string if it is found in array or -1 if not found.
var checkboxValues = ["large-car", "small-car", "automatic"];
var carType = ["large-car","automatic","some car"];
function searchMatch(carType) {
var result = new Array();
for(var i=0;i < carType.length;i++) {
// If match found push the match to the result array.
if(checkboxValues.indexOf(carType[i]) != -1){
result.push(carType[i])
}
}
return result ;
}
As a result you will get ["large-car","automatic"];
if you use underscoreJs may look like this
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ['small-car','automatic'];
var result=_.any(checkboxValues,function(checkbox){
return _.any(carType,function(carT){ return carT==checkbox;});
});
Try this jQuery solution:
<script type="text/javascript">
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ["large-car"];
if ($.inArray(carType[0].toString(), checkboxValues ) == -1) {
return false;// if not exists
}
</script>
(forgive me if I use slightly incorrect language - feel free to constructively correct as needed)
There are a couple posts about getting data from JSON data of siblings in the returned object, but I'm having trouble applying that information to my situation:
I have a bunch of objects that are getting returned as JSON from a REST call and for each object with a node of a certain key:value I need to extract the numeric value of a sibling node of a specific key. For example:
For the following list of objects, I need to add up the numbers in "file_size" for each object with matching "desc" and return that to matching input values on the page.
{"ResultSet":{
Result":[
{
"file_size":"722694",
"desc":"description1",
"format":"GIF"
},
{
"file_size":"19754932",
"desc":"description1",
"format":"JPEG"
},
{
"file_size":"778174",
"desc":"description2",
"format":"GIF"
},
{
"file_size":"244569996",
"desc":"description1",
"format":"PNG"
},
{
"file_size":"466918",
"desc":"description2",
"format":"TIFF"
}
]
}}
You can use the following function:
function findSum(description, array) {
var i = 0;
var sum = 0;
for(i = 0; i < array.length; i++) {
if(array[i]["desc"] == description && array[i].hasOwnProperty("file_size")) {
sum += parseInt(array[i]["file_size"], 10);
}
}
alert(sum);
}
And call it like this:
findSum("description1", ResultSet.Result);
To display an alert with the summation of all "description1" file sizes.
A working JSFiddle is here: http://jsfiddle.net/Q9n2U/.
In response to your updates and comments, here is some new code that creates some divs with the summations for all descriptions. I took out the hasOwnProperty code because you changed your data set, but note that if you have objects in the data array without the file_size property, you must use hasOwnProperty to check for it. You should be able to adjust this for your jQuery .each fairly easily.
var data = {};
var array = ResultSet.Result;
var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;
//Sum the sizes for each description
for(i = 0; i < array.length; i++) {
currentDesc = array[i]["desc"];
currentSize = parseInt(array[i]["file_size"], 10);
data[currentDesc] =
typeof data[currentDesc] === "undefined"
? currentSize
: data[currentDesc] + currentSize;
}
//Print the summations to divs on the page
for(sumItem in data) {
if(data.hasOwnProperty(sumItem)) {
sizeDiv = document.createElement("div");
sizeDiv.innerHTML = sumItem + ": " + data[sumItem].toString();
document.body.appendChild(sizeDiv);
}
}
A working JSFiddle is here: http://jsfiddle.net/DxCLu/.
That's an array embedded in an object, so
data.ResultSet.Result[2].file_size
would give you 778174
var sum = {}, result = ResultSet.Result
// Initialize Sum Storage
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] = 0;
}
// Sum the matching file size
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] += parseInt(result[i]["file_size"]
}
After executing above code, you will have a JSON named sum like this
sum = {
"description1": 20477629,
"description2": 1246092
};
An iterate like below should do the job,
var result = data.ResultSet.Result;
var stat = {};
for (var i = 0; i < result.length; i++) {
if (stat.hasOwnProperty(result[i].cat_desc)) {
if (result[i].hasOwnProperty('file_size')) {
stat[result[i].cat_desc] += parseInt(result[i].file_size, 10);
}
} else {
stat[result[i].cat_desc] = parseInt(result[i].file_size, 10);
}
}
DEMO: http://jsfiddle.net/HtrLu/1/
here is my javascript:
var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
obj = JSON.parse(json);
var arrayobj = obj.GetReportIdResult.length;
alert (arrayobj);
I want to count how many type in the same bulan value, (e.g. there are 3 type = CHEESE1K, UHT, and ESL in bulan = 4)
how to do that?
There's still a typo in your JSON: you've got two commas in a row between the first two "bulan":"6" objects. But assuming you fix that...
If you're asking how to count distinct types for a particular bulan value you can do something like this:
function countTypesForBulan(resultArray, bulanVal) {
var i,
types,
count = 0;
for (i=0, types = {}; i < resultArray.length; i++)
if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
types[resultArray[i].type] = true;
count++;
}
return count;
}
console.log( countTypesForBulan(obj.GetReportIdResult, "4") ); // logs 3
The above loops through the array looking for a particular bulan value, and when it finds one it checks if it has already seen the associated type - if not, it adds it to the types object and increments the counter.
Demo: http://jsfiddle.net/pAWrT/
First of all, put the JSON into a string,
else your example code wont work.
var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},,{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
Then,
Iterate with for and count in a variable or a hashmap.
Since GetReportIdResult is an array, you can:
for( var i : obj.GetReportIdResult ){
obj.GetReportIdResult[i] ... // Use at will.
This will give you a map object which will contain the count for each bulan value. For example, map['4'].count will return 3.
var i, row, arr = obj.GetReportIdResult, map = {};
for (i = 0; i < arr.length; i++) {
row = arr[i];
map[row.bulan] = map[row.bulan] || {count: 0};
if (map[row.bulan][row.type] === undefined) {
map[row.bulan][row.type] = row.type;
map[row.bulan]['count'] += 1;
}
}
console.log (JSON.stringify(map));
JSFiddle here.
I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}