I fail to see why this date comparison is not working in js. I have linked a json file with items that have dateproperties to the nggrid. This is what the refresh function looks like:
$scope.refresh = function() {
$http.get('data.jon').success(function(data) {
//$scope.myData = data;
//$scope.myData.splice(0,1);
var i=0;
data.forEach(
function(item) {
i++;
console.log(i);
var itemDate = new Date(item.date).valueOf();
var compareDate = new Date('1/1/2025').valueOf();
if (itemDate < compareDate) {
debugger;
console.log(itemDate);
console.log(compareDate);
$scope.myData.push(item);
}
});
});
};
The data for the grid looks like this:
[
{
"name": "Moroni",
"age": 50,
"date":"1/1/2015"
},
{
"name": "Tiancum",
"age": 43,
"date":"1/1/2016"
},
{
"name": "Jacob",
"age": 27,
"date":"1/1/2017"
},
{
"name": "Nephi",
"age": 29,
"date":"1/1/2018"
},
{
"name": "Enos",
"age": 34,
"date":"1/1/2019"
}
]
I would expect to see 5 dates to be displayed in my table because they all satisfy the request?
Here is a plunker:http://plnkr.co/edit/e4ua6k?p=preview
Why don't you do this instead:
var itemDate = new Date(item.date);
var compareDate = new Date('1/1/2025');
if (itemDate < compareDate) {
.....
}
Why not compare timestamp directly instead like below :-
var itemDate = new Date(item.date).getTime();
var compareDate = new Date('1/1/2025').getTime();
if (itemDate < compareDate) {
}
Related
I have 2 maps and I want to get the missing elements as a list. For example:
var map1= [
{"name":"name1","email":"name1#email.com"},
{"name":"name2","email":"name2#email.com"},
{"name":"name3","email":"name3#email.com"},
];
var map2= [
{"name":"name1","email":"name1#email.com"},
{"name":"name2","email":"name2#email.com"},
];
Output: [{"name":"name3","email":"name3#email.com"}]
I tried this approach:
var removedElements = map2.where((element) =>
!map1
.contains(element['email']))
.toList();
but it doesn't work. Any help would be great.
try with this
void main() {
var map1 = [
{"name": "name1", "email": "name1#email.com"},
{"name": "name2", "email": "name2#email.com"},
{"name": "name3", "email": "name3#email.com"},
];
var map2 = [
{"name": "name1", "email": "name1#email.com"},
{"name": "name2", "email": "name2#email.com"},
];
var removedElements = [];
var k;
for (var i in map2) {
for (var j in map1) {
if (i["email"] != j["email"]) {
k = j;
}
}
removedElements.add(k);
}
print(removedElements.toSet().toList());
}
Another approach
var removedElements =
map2.where((element) {
for(var i in map1){
if(i["email"] == element["email"]){
return false;
} else{
return true;
}
}
}).toList();
print(removedElements);
output
: [{name: name3, email: name3#email.com}]
Hi i have excel upload functionality when i upload the excel that should save in to the mongodb(database). I have taken the excel cell value as json stringify and also i converted that as parse. now i don't how to get that json length value.
here i have attached my code
function to_json(workbook) {
debugger;
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
$scope.Sheetname=sheetName; // here sheet name is excel sheet name
MainSheetName=sheetName;
var roa = X.utils.sheet_to_json(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return result;
}
var HTMLOUT = document.getElementById('htmlout');
function to_html(workbook) {
HTMLOUT.innerHTML = "";
workbook.SheetNames.forEach(function(sheetName) {
var htmlstr = X.write(workbook, {sheet:sheetName, type:'binary', bookType:'html'});
HTMLOUT.innerHTML += htmlstr;
});
}
var tarea = document.getElementById('b64data');
function b64it() {
if(typeof console !== 'undefined') console.log("onload", new Date());
var wb = X.read(tarea.value, {type: 'base64',WTF:wtf_mode});
process_wb(wb);
}
window.b64it = b64it;
var OUT = document.getElementById('out');
var global_wb;
function process_wb(wb) {
global_wb = wb;
var output = "";
var output1 = "";
switch(get_radio_value("format")) {
case "json":
output = JSON.stringify(to_json(wb), 2, 2);
output1=JSON.parse(output);
break;
case "form":
output = to_formulae(wb);
break;
case "html": return to_html(wb);
default:
output = to_csv(wb);
}
if(OUT.innerText === undefined) OUT.textContent = output;
else OUT.innerText = output;
debugger;
$scope.MainInfo=output1; // this return whole data
console.log(output1);
$scope.jsondata=output1.Sheet1[0].length;// this returns undefined. Here sheet name is excel file sheetName it will taken from excel.
console.log($scope.jsondata);
my output is showing like this
{
"Sheet1": [
{
"Name": "xxx",
"Age": "22",
"Salary": "222222"
},
{
"Name": "yyy",
"Age": "23",
"Salary": "232323"
},
{
"Name": "zzz",
"Age": "23",
"Salary": "232323"
}
]
}
now i want length of Sheet1 how can i get that. can any one tell me
If you were to assign your output to obj getting the length of Sheet1 would be as simple as going obj.Sheet1.length
Try this :
var output = {
"Sheet1": [{
"Name": "xxx",
"Age": "22",
"Salary": "222222"
}, {
"Name": "yyy",
"Age": "23",
"Salary": "232323"
}, {
"Name": "zzz",
"Age": "23",
"Salary": "232323"
}]
};
var newArr = $.grep(output1.Sheet1, function( value, index ) {
if(n.Name == "xxx") {
return n;
}
});
console.log(newArr)
You can use angular.fromJson(yourJson).length functionality.
In your case, it should be angular.fromJson($scope.jsondata).length.
As per my understanding from above code, your are getting response into JSON string format so you can't perform JSON operation over it. try to convert json string to json object using JSON.parse method.Below is sample code in node js.
var parseData = JSON.parse(output1);
var parsedata1 = parseData.Sheet1;
for(var namevalue=0;namevalue<parsedata.length;namevalue++){
console.log("Name value: "+parsedata1[namevalue].Name);
}
I want to push below data. I want order the items, it consists of following fields:
var OrderItem = {"itemid":item.itemid,"itemname":item.itemname,"qty":1,"itemprice":item.itemprice};
But I want to Store Like this
{
"Items": [
{
"itemid": 50,
"itemname": "sample",
"itemprice": 124,
"qty": 1
},
{
"itemid": 52,
"itemname": "sample",
"itemprice": 124,
"qty": 1
}
]
}
Controllers:
$scope.addnew=function(item){
var OrderItem= {"itemid":item.itemid,"itemname":item.itemname,"qty":1,"itemprice":item.itemprice};
NewOrderService.addOrderitems(OrderItem);
}
}
Services:
servctrl.service("NewOrderService", function(NewOrderFactory) {
this.addOrderitems = function(orderitemnew) {
NewOrderFactory.AddOrdernew(orderitemnew);
}
});
Factorys:
factmodule.factory("NewOrderFactory",function(){
var orderitemsnew=[];
return {
AddOrdernew:function(orderitemnew){
orderitemsnew.push(orderitemnew);
}
}
});
How to Achieve this?
probably like this?
factmodule.factory("NewOrderFactory",function(){
var orderitemsnew={
items = [];
};
return{
AddOrdernew:function(orderitemnew){
orderitemsnew.items.push(orderitemnew);
},
getOrderItemsNewList: function() {
return orderitemsnew;
}
};
});
I have a simple function below using which am trying create dynamic div containing a d3 chart for each row from the given input "json.res_full_sk"
However, when I use apply in Angularjs, am losing the historic data that is being assigned to dyndata object.
<script>
var app = angular.module('rpPlotExampleApp', ['ui.rpplot']);
app.controller('rpPlotCtrl', function ($scope) {
$scope.dyndata={};
$scope.assign_sk = function (testjsobj) {
alert('From Angular JS'+ JSON.stringify(testjsobj));
$scope.dyndata=testjsobj;
};
});
</script>
<script type="text/javascript">
jsonList = [];
jsonList.res_full_sk = [
{ "tid": 20, "sk": [{ "name": "Banking", "value": 40, "id": 0 }, { "name": "Housing", "value": 4, "id": 1 }, { "name": "Home", "value": 4, "id": 2 }, { "name": "NET", "value": 4, "id": 3 }] },
{ "tid": 22, "sk": [{ "name": "Movie", "value": 12, "id": 0 }, { "name": "Movie2", "value": 4, "id": 1 }, { "name": "Housing", "value": 4, "id": 2 }, { "name": "Banking", "value": 4, "id": 3 }, { "name": "C", "value": 4, "id": 4 }] },
{ "tid": 24, "sk": [{ "name": "Housing", "value": 4, "id": 0 }, { "name": "Home", "value": 4, "id": 1 }, { "name": "Banking", "value": 4, "id": 2 }] }
];
arr = [];
function getObjContents(i) {
arr = $.grep(jsonList.res_full_sk, function (e) {
return e.tid == i;
});
var str = "";
for (var i = 0; i < arr[0].sk.length; i++) {
str += ","+ JSON.stringify(arr[0].sk[i]);
}
str=str.substring(1);
str = "[" + str + "]";
str_obj=JSON.parse(str);
str_fin = {};
str_obj.forEach(function (e, i) {
str_fin['d' + i] = e;
});
return str_fin;
}
function insertDiv(Num) {
array = [];
var ar1 = Num.replace('[', '');
array = JSON.parse("[" + ar1 + "]");
var i = 0;
for (i; i < array.length; i++) {
js_data={};
js_data=getObjContents(array[i]);
testjsobj=js_data;
var scope = angular.element(document.getElementById("rpPlotCtrl")).scope();
scope.$watch("dyndata", function (oldval, newval) {
}, true);
scope.$apply(function () {
scope.dyndata = js_data;
});
var id_num;
id_num = array[i];
var rChart = angular.element(document.getElementById("sktemp"));
rChart.injector().invoke(function ($compile) {
$('<div obj></div>').insertAfter("#sktemp")
var obj = $('[obj]'); // get wrapper
var scope1 = $('[obj]').scope();
// generate dynamic content
alert(JSON.stringify(scope1.dyndata));
obj.html("<div class='skpro' id='skpro" + id_num + "' name='cn'><div class='skprovis' id='skprovis" + id_num + "' >Hello " + id_num + "<div class='half-plot' style='height:95%;width:95%;margin-top:0px;margin-left:5px;'><rp-plot dsn='dyndata' point-radius='1.5' scale='log' labelled='true' class='plot-rp-plot'></rp-plot></div></div></div>");
// compile!!!
console.log(obj.contents());
$compile(obj.contents())(scope1);
scope1.$apply();
});
}
}
</script>
The problem is dyndata is being changed for each value of i in the for loop, and thus the d3 chart is updated with the lastly assigned dyndata object.
As I see the dyndata object is being assigned with different values each time for loop executes, but it is not remaining but changes with the next value of dyndata to all the charts that were created.
How can I get the historic data to persist for dyndata that is already rendered for each for loop execution?
Am new to Angularjs and not very sure how I can make use of Angular.copy() for this scenario.
Problem seems to be with below code -
var scope = angular.element(document.getElementById("rpPlotCtrl")).scope();
scope.$watch("dyndata", function (oldval, newval) {
}, true);
scope.$apply(function () {
scope.dyndata = js_data;
});
as soon as I assign new js_data value to dyndata, all the existing charts gets updated with new value.
I tried using angular.copy(scope.dyndata)=js_data.. But it didn't work out.
Can you please suggest me?
I am trying to create an angular service but getting an error. This is the service:
var app = angular.module('plunker', []);
// Filter Service that returns records with crdamt positive:
app.factory('FilterService', function() {
return function(d) {
var filteredData = [];
console.log(d);
d.forEach(function(item)
{
if (item.cramt > 0) {
filteredData.push(item);
}
});
return filteredData;
}
});
In my unit test however we get:
it('should return transactions where credit is positive', function() {
var jsonData = {
"transactions": [{
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
}, {
"date": "1/1/2002",
"desc": "Transaction",
"cramt": 110,
"dbamt": 10
}]
};
var filteredRecords = FilterService(jsonData);
expect(filteredRecords).toEqual({
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
});
});
Why do I get an error:
TypeError: d.forEach is not a function
plunkr:http://plnkr.co/edit/jdg0wEj1zSDTbqojBAoc?p=preview
forEach method is available on arrays.
Looking at your jsonData you can do this:
app.factory('FilterService', function() {
return function(data) {
var filteredData = [];
console.log(data.transactions);
data.transactions.forEach(function(item)
{
if (item.cramt > 0) {
filteredData.push(item);
}
});
return filteredData;
}
});
P.S: Please read the error messages. It clearly says that d.forEach is not a functions. It is like trying to define an object like:
var person = {
'name':'Paul'
};
and trying to access person.height(). The height is not a property of person object and you are trying to access undefined property as a function.
More info
Just try. I'm expecting variable d as an array.
angular.forEach(d, function(item){
if (item.cramt > 0) {
filteredData.push(item);
}
});
You're not using the right syntax for forEach function of angular js. Please refer this angular.forEach directive
Your test is trying to filter the entire object instead of the array of transactions.
var filteredRecords = FilterService(jsonData);
expect(filteredRecords).toEqual({
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
});
should be
var filteredRecords = FilterService(jsonData.transactions);
expect(filteredRecords).toEqual([{
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
}]);
Please look at the updated plnkr. forEach is used for the arrays only and your 'd' returns an object.
Following is the link to the plnkr :
``http://plnkr.co/edit/o65e0xEsBiW0jpawhGse?p=preview
you can define filter in this way.
app.factory('FilterService', function() {
return function(d) {
var filteredData = [];
var boolDataISFound = false;
console.log(d.transactions)
d.transactions.forEach(function(item,index)
{
if (item.cramt > 0) {
filteredData.push(item);
}
});
return filteredData[0];
}
});
and here is the expectation
it('should return transactions where credit is positive', function() {
var jsonData = [{
"transactions": [{
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
}, {
"date": "1/1/2002",
"desc": "Transaction",
"cramt": 110,
"dbamt": 10
}]
}];
var filteredRecords = FilterService(jsonData[0]);
expect(filteredRecords).toEqual({
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
} );
});
Here is the Plunker