Am having some id's in my "var " . That id's are all present in a Static data which is having both id with names . What i'm trying to do is i have to find out the name's of my id's and print the name's alone . I'm trying with many Underscore js method's but failed . Can some one clarify/Suggest me pls .
var CatePeri =[];
var cate =[];
// var CateName=[];
$scope.getCategories = function() {
for (var i = 0 ; i < mainSteps.length; i++) {
for (var j = 0; j<mainSteps[i].steps.length; j++) {
var CatePeri= mainSteps[i].steps[j].category;
cate.push(CatePeri);
// var CateName =_.findWhere(mainSteps[i].category, cate);
// var CateName =_.where(mainSteps[i].category, cate);
}
}
return cate; // It return Id's Now
// But i have to Return the name's of that id's
Here
var CatePeri is having Whole Category id's with Names,
var cate is having Category id's alone,
Instead of returning id's i need to Return their names .
var CatePeri =[];
var cate =[];
// var CateName=[];
$scope.getCategories = function() {
for (var i = 0 ; i < mainSteps.length; i++) {
for (var j = 0; j<mainSteps[i].steps.length; j++) {
var CatePeri= mainSteps[i].steps[j].category;
cate.push(CatePeri);
// var CateName =_.findWhere(mainSteps[i].category, cate);
// var CateName =_.where(mainSteps[i].category, cate);
}
}
return _.pick(_.values(cate), 'name'); // It return Id's Now
// But i have to Return the name's of that id's
I assumed,you Have a static JSON like below
var staticJson ={
id:'5rtf567',
name:'S'
}
Use underscore.js _.where option like,
// If you have the multiple object to find out the name put it the below code in `for` loop and try it
var nameOfId = _.where(staticJson ,{id:staticJson.id}
console.log('If you Want Whole Object',angular.toJson(nameOfId));
console.log('If you Want Name',angular.toJson(nameOfId.name));
Related
I have a script that iterates through 2 spreadsheets, finds duplicate values in column A, then appends the row of these duplicate values to another sheet.
I actually want this script to do a similar thing, but append the rows that are NOT duplicates instead of the ones that are. How can I alter it so that it sends the non duplicates to the "New Students" sheet"? I tried changing the == to !==. But that sends the whole list. I have been searching around for a while and I know it's probably an easy fix.
Thanks so much!
Brandon
function compareandupdate() {
var s1 = SpreadsheetApp.openById("XXXXXX-vvxyewdki0J9tGqJl9_f-wZE0zOboQRIscLAA").getSheetByName('Updated Student List');
var s2 = SpreadsheetApp.openById("XXXXXX-yB9Xm1J5RKWS7NF23vD-NTUeIgspbctj3leW4").getSheetByName('Master Student List');
var s3 = SpreadsheetApp.openById("XXXXXX-yB9Xm1J5RKWS7NF23vD-NTUeIgspbctj3leW4").getSheetByName('New Students');
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var resultArray = [];
for(var n=0; n < values1.length ; n++){
var keep = false;
for(var p=0; p < values2.length ; p++){
Logger.log(values1[n][0]+' =? '+values2[p][0]);
if( values1[n][0] == values2[p][0]){
resultArray.push(values1[n]);
Logger.log('true');
break ;// remove this if values are not unique and you want to keep all occurrences...
}
}
}
s3.getRange(+1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
If you prefer to keep your existing structure (which I think I wrote some time ago ;-) and btw has an unnecessary variable (keep)!) you can use this modified version of your code :
function compareAndUpdate() {
var s1 = SpreadsheetApp.openById("XXXXXX-vvxyewdki0J9tGqJl9_f-wZE0zOboQRIscLAA").getSheetByName('Updated Student List');
var s2 = SpreadsheetApp.openById("XXXXXX-yB9Xm1J5RKWS7NF23vD-NTUeIgspbctj3leW4").getSheetByName('Master Student List');
var s3 = SpreadsheetApp.openById("XXXXXX-yB9Xm1J5RKWS7NF23vD-NTUeIgspbctj3leW4").getSheetByName('New Students');
// var definition for easier testing purpose
// var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
// var s2 = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];
// var s3 = SpreadsheetApp.getActiveSpreadsheet().getSheets()[2];
var values1 = s1.getDataRange().getValues();
var values2 = s2.getDataRange().getValues();
var resultArray = [];
for(var n=0; n < values1.length ; n++){
var keep = true;
for(var p=0; p < values2.length ; p++){
Logger.log(values1[n][0]+' =? '+values2[p][0]);
if( values1[n][0] == values2[p][0]){
keep = false;// if same value in first column in s2 then don't keep (you can modify this condition to your needs, extend to whole row or other columns for example )
break;
}
}
if(keep){
resultArray.push(values1[n]);// keep only values from s1 that are not in s2
}
}
s3.getRange(+1,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
You could try this
function contains(array, entry) {
for(var p=0; p < array.length ; p++){
if(array[p][0] === entry){
return true;
}
}
return false;
}
for(var n=0; n < values1.length ; n++) {
if(!contains(values2, values1[n][0])) {
resultArray.push(values1[n]);
}
}
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.
I have an array which is
var mycart = [{"id":"1","quantity":"10"},{"id":"6","quantity":"20"},{"id":"3","quantity":"30"},{"id":"4","quantity":"40"}];
//new id's which should be updated
var newid = "6";
var newquantity = "5";
Every-time on cart update i want to update the id and value,if id exists i need to update quantity if doesn't i have to create a new object of id,quantity.
Now,i am adding newid which is 6,as you can see id=6 exist in array so it should just update like this -
for(var x=0; x < mycart.length; x++){
if(mycart[x].id == newid ){
var tmpq = mycart[x].quantity;
mycart[x].quantity = parseInt(tmpq) + parseInt(q);
}
else{
alert(mycart[x].id+' = this is not what you are searching');
}
}
now output is :
var mycart = [{"id":"1","quantity":"10"},{"id":"6","quantity":"25"},{"id":"3","quantity":"30"},{"id":"4","quantity":"40"}];
Now i need help to create new object,if that id doesn't exist in the mycart array.
If i use
//new id's which should be created
var newid = "2";
var newquantity = "15";
var temparr = new Array();
var tmpobj ={};
tmpobj["id"]= newid ;
tmpobj["quantity"] = newquantity ;
temparr.push(tmpobj);
mycart.push(temparr);
within the for loop it will create mycart.length times,then i have to filter with $unique() jQuery API which is bad method to follow.
All i need is to create new object with id:value,quantity:value if it doesn't exists,if it exists then just update. Update part working,create part not able to,
Use a variable to detect if you found an old item:
var found = false;
for(var x=0; x < mycart.length; x++){
if(mycart[x].id == newid ){
var tmpq = mycart[x].quantity;
mycart[x].quantity = parseInt(tmpq) + parseInt(q);
found = true;
break;
}
}
if (!found) {
mycart.push ({ id: newid, quantity: newquantity });
}
It would be simpler if you made mycart an object whose keys are the IDs, so you wouldn't have to do a linear search. It would be like this:
var mycart = {
"1": { quantity: 10 },
"6": { quantity: 20 },
...
};
Then your code would be:
if (mycart.hasOwnProperty(newid)) {
mycart[newid] += newquantity;
} else {
mycart[newid] = { quantity: newquantity };
}
What about something like this?
updateCart = function(newid,newquantity,cart){
for(var x=0; x < mycart.length; x++){
if(mycart[x].id == newid ){
var tmpq = cart[x].quantity;
cart[x].quantity = parseInt(tmpq) + parseInt(newquantity);
return;
}
else{
alert(mycart[x].id+' = this is not what you are searching');
}
}
cart.push({"id":newid,"quantity":newquantity});
return;
};
This avoids any 'flag' variables, which IMHO is nice. You could then call it like so:
updateCart("6","5",mycart); //[..{"id":"6","quantity":"25"}..]
updateCart("10","7",mycart); //[..{"id":"10","quantity":"7"}](new array member)
updateCart("1","5",mycart); //[{"id":"1","quantity":"15"}...]
I must agree with the others, though, when they say that you might want to use some sort of key so you don't have to iterate through the array each time.
To create a new item, I would do:
var match = false;
for (var x = 0; x < mycart.length; x++) {
var id = mycart[x].id;
//If there's a match, then item already exists
if (id === newid) {
//Update it
var tmpq = mycart[x].quantity;
mycart[x].quantity = parseInt(tmpq) + parseInt(q); //I'm not sure what q is, but I will leave it since you said it works in your code
match = true;
}
}
//If no match found, create new
if (!match) {
var newItem = {};
newItem.id = newid;
newItem.quantity = newquantity;
mycart.push(newItem);
}
Since there is no reason for the array to contain multiple objects with the same id, I suggest you use an object as the root of the variable, using the id as an array key (+ prefix to avoid confusions) :
var mycart = {"item_1":{"id":"1","quantity":"10"},"item_6":{"id":"6","quantity":"20"},...};
This way you can set/get quantity with mycart["item_"+id].quantity
so you can update it like that :
function updateQuantity(id, quantity){
if(!mycart["item_"+id]){
// create item in cart
mycart["item_"+id] = {"id":id};
}
// update quantity
mycart["item_"+id].quantity = quantity;
}
I want to make json object of html table in javascript.Currently I am able to read the each cells value in javascript, the only problem is that I am not able to retrieve as per my need so think of any suggestion here. Currently getting value like:
var x = document.getElementById("tableId");
for (var i = 0; i < x.rows.length; i++) {
for (var j = 0; j < x.rows[i].cells.length; j++){
tableJsonDTO[name] = x.rows[i].cells[j].innerHTML;
}
}
This is how i am able to read the each cell value.The table format is as follow:
header: company_1 company_2 company_3
Question1 answer_1 answer_1 answer_1
Question2 answer_2 answer_2 answer_2
and so on.How can i read the value so that i can get object like:
var obj = [{spname:"company_1",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_2",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_3",qalist:[{question:"",answer:""},{question:"",answer:""}]}]
Please give some suggestion.
You simply need to change the way you put values to tableJsonDTO. Demo.
document.getElementById('toJSON').addEventListener('click', function(){
var table = document.getElementById('mytable'),
names = [].slice.call(table.rows[0].cells),
values = [].slice.call(table.rows, 1),
out = {};
values.forEach(function(row) { //iterate over values
var cells = row.cells,
caption = cells[0].innerHTML; //get property name
[].forEach.call(cells, function(cell, idx) { //iterate over answers
var value = {},
arr;
if(!idx) return; //ignore first column
value[caption] = cell.innerHTML; //prepare value
//get or init array of values for each name
arr = out[names[idx].innerHTML] || (out[names[idx].innerHTML] = []);
arr.push(value);
});
});
console.log(out);
});
(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/