angularjs ng-options with formate date delete duplicates - javascript

I made a filter for the field DataIscr on this json :
[
{
"IdPers": "1067",
"CognNome": "JANE SMITH",
"Sex": "F",
"DataIscr": "1949-12-29T00:00:00+01:00"
},
{
"IdPers": "1093",
"CognNome": "JOHN SMITH",
"Sex": "M",
"DataIscr": "1969-12-02T00:00:00+01:00"
},
{
"IdPers": "1093",
"CognNome": "JANE SMITH",
"Sex": "F",
"DataIscr": "1969-06-17T00:00:00+01:00"
}
]
and I used the format date: 'yyyy' to display only the year:
<label for="DataIscr">DataIscr:</label>
<select style="width:200px" data-ng-options="Person.DataIscr as Person.DataIscr|date:'yyyy' for Person in OutAnagrafica" id="DataIscr" data-ng-model="filter.DataIscr" class="form-control input-sm"></select>
plunker:http://plnkr.co/edit/ED1v7czBosNSpCYxKW7n?p=preview
How can I delete the duplicates?? I want to filter object with the same year and the filter 'unique' from angular Ui doesn't work. How can I do??

Sidos Check this out , i used 'angular.filter' modules unique filter .
<select style="width:200px" data-ng-options="Person for Person in OutAnagrafica| removeDuplicates " id="DataIscr" data-ng-model="filter.DataIscr" class="form-control input-sm"></select>
App.filter('removeDuplicates', function ($filter) {
return function (input) {
var dates=[];
angular.forEach(input,function(item,index)
{
dates.push($filter('date')(item.DataIscr,'yyyy'));
})
console.log(dates);
return $filter('unique')(dates);
};
});
http://embed.plnkr.co/slrtdv/preview

Instead of using the angular ui filter, write your own custom filter for filtering the date values. since the UI filter check for the whole value, it does not support the format the values for duplicate removal. below is the fiddle link for your scenario.
JS
var app = angular.module('myApp', []);
app.controller('OutAnCtrl', function ($scope) {
$scope.OutAnagrafica = [{
"IdPers": "1067",
"CognNome": "JANE SMITH",
"Sex": "F",
"DataIscr": "1949-12-29T00:00:00+01:00"
}, {
"IdPers": "1093",
"CognNome": "JOHN SMITH",
"Sex": "M",
"DataIscr": "1969-12-02T00:00:00+01:00"
}, {
"IdPers": "1093",
"CognNome": "JANE SMITH",
"Sex": "F",
"DataIscr": "1969-06-17T00:00:00+01:00"
}];
});
app.filter('customDateUnique', function ($filter) {
return function (arr, field) {
return _.uniq(arr, function (a) {
return $filter('date')(a.DataIscr, 'yyyy');
});
};
});
HTML
<body>
<div>
<div data-ng-controller="OutAnCtrl">
<label for="DataIscr">DataIscr:</label>
<select style="width:200px" data-ng-options="Person.DataIscr as Person.DataIscr|date:'yyyy' for Person in OutAnagrafica | customDateUnique" id="DataIscr" data-ng-model="filter.DataIscr" class="form-control input-sm"></select>
</div>
</div>
</body>
http://jsfiddle.net/1tw3zg9s/1/

After seeing your comment, I changed my answer.
You can define a new $scope.filtered array and upon ajax success do:
$http.get('OutAnagrafica.json')
.success(function (data) {
$scope.OutAnagrafica = data;
$scope.OutAnagrafica.forEach(function(item) {
if (yearUnique($scope.filtered, item)) {
$scope.filtered.push(item);
}
});
});
And you have the function yearUnique:
function yearUnique(arr, item) {
var year = item.DataIscr.substring(0, 4);
var res = true;
if (arr.forEach(function(i) {
if (i.DataIscr.indexOf(year) > -1) {
console.log('false');
res = false;
}
}));
return res;
}
And on the HTML:
<tr data-ng-repeat="Person in filtered">
...
</tr>
Plunker

Related

Merge 2 object arrays in json files by key

I'm trying to combine 2 object array in javascript/jquery matching them by the same key (code). These object arrays are stored in 2 separate json files.
I've cut these down as the files are long
Thanks in advance if anyone can help.
Object 1:
[{
"city": "london",
"selfemployed": {
"job" :"Builder",
"code": "abc"
},
"company" : {
"job": "Shopkeeper",
"code": "def"
}
}]
Object 2:
[{
"code": "abc",
"participant": {
"firstname" : "Joe",
"lastname" : "Blogs"
}
},
{
"code": "def",
"participant": {
"firstname" : "Anna",
"lastname" : "Smith"
}
}]
Needed result:
[{
"city": "london",
"selfemployed": {
"job" :"Builder",
"code": "abc",
"participant": {
"firstname" : "Joe",
"lastname" : "Blogs"
}
},
"company" : {
"job": "Shopkeeper",
"code": "def",
"participant": {
"firstname" : "Anna",
"lastname" : "Smith"
}
}
}]
One of my issues is that I'm unable to return the object from the .json files
var file1 = 'url/file1.json';
var file1 = 'url/file2.json';
const joinJson = (file1, file2) => {
$.getJSON(file, function(data1) {
return data1;
});
$.getJSON(file2, function(data2) {
return data2;
});
// do stuff with data1 and data2
}
console.log(joinJson());
You could take a Map and build new objects for the result by selecting the wanted code information for the new object.
This proposal uses rest properties of an object with babel for older user agents.
var cities = [{ city: "london", selfemployed: { job: "Builder", code: "abc" }, company: { job: "Shopkeeper", code: "def" } }],
codes = [{ code: "abc", participant: { firstname: "Joe", lastname: "Blogs" } }, { code: "def", participant: { firstname: "Anna", lastname: "Smith" } }],
codesMap = new Map(codes.map(({ code, participant }) => [code, participant])),
result = cities.map(
({ city, ...items }) =>
Object.assign({ city }, ...Object.entries(items).map(
([k, v]) => ({ [k]: Object.assign({}, v, codesMap.get(v.code)) })
))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The problem is that you're getting the files asynchronously, and returning data in the callback of that async operation, which goes nowhere. Something like this would be better:
var file1 = 'url/file1.json';
var file1 = 'url/file2.json';
const joinJson = (file1, file2) => {
$.getJSON(file, function(data1) {
// async operation 1 complete. Start operation 2.
$.getJSON(file2, function(data2) {
// async operation 2 complete
// data1 and data2 are now available here
console.log("Data 1:", data1);
console.log("Data 2:", data2);
// This will merge the keys of both objects
// but you can replace it with custom merging logic
var merged = Object.assign(data1, data2);
console.log(merged);
});
});
}
The problem here is that you can't do something like console.log(joinJson());. You may very well need something like a Promise.

Access Nested JSON objects and their attributes Angularjs

I am a new bie to angular and trying to learn it.
I am trying to display user data from a webservice that I received as response.
here's the response
{
"Users": {
"SearchTerm": "angularjs ra1",
"ResultsPerPage": "20",
"RecordStartNumber": "0",
"TotalEstimatedResults": "6",
"User": [{
"WWID": "123456",
"Email": "mary.p.wilson#yahoo.com",
"BusinessTitle": "Project Manager",
"Name": "Mary Wilson",
"firstname": "Mary",
"lastname": "Wilson",
"idsid": "RAP"
}, {
"WWID": "1234567",
"Email": "steve.r.smith#gmail.com",
"BusinessTitle": "Quality Assurance",
"Name": "Steve Smith",
"firstname": "Steve",
"lastname": "Smith",
"idsid": "DRPRESTO"
}, {
"WWID": "12345678",
"Email": "jon.jones#gmail.com",
"BusinessTitle": "Chef",
"Name": "Jon Jones",
"firstname": "Jon",
"lastname": "Jones",
"idsid": "JJONES"
}]
}
}
MyScript.js
var Application = angular.module('TestModule', []);
Application.controller('TestController', function ($scope,$http) {
$scope.TestValue = "Hello World from Controller";
$scope.Myfunc = function asdf() {
$http.get('http://unifiedcollaborationprofile.gots.com/search/expert/data/v2/?apiKey=SECRET&listFromPersonNumber=0&numPeoplePerPage=20&query=angularjs+ra1&returnFriendlyResults=true').then(
function (response) {
$scope.users = [];
angular.forEach(response.Users, function (value, key) {
$scope.users.push(value);
});
});
};
});
Page.html
<!DOCTYPE html>
<html ng-app="TestModule">
<head>
<title></title>
<meta charset="utf-8" />
</head>
{{2+3}}
<body>
<div ng-controller="TestController">
{{2+3}}
{{TestValue}}
<input type="text" ng-model="TestValue" />
<input type="button" value="Click Me To Get All Users!!!!" ng-click="Myfunc()" />
<ul ng-repeat="k in users">
<li>WWID:{{k.WWID}} Email:{{k.Email}} Name:{{k.Name}} IDSID:{{k.idsid}}</li>
</ul>
</div>
</body>
</html>
<script src="scripts/angular.min.js"></script>
<script src="scripts/MyScripts/MyScript.js"></script>
But nothing gets rendered on my Page.
I am not sure if I am rightly accessing the nested User object in Users Collection of JSON and its properties.
what am I missing.
I've created plunker with your code and all I did to make it work is to change it to this:
$scope.Myfunc = function asdf() {
$http.get('test.json').then(function(response) {
$scope.users = [];
angular.forEach(response.data.Users.User, function(value, key) {
$scope.users.push(value);
});
});
};
http://plnkr.co/edit/Fu1tCnhxSn9dgBXtTJ9r?p=preview
You must remember that then after http promise gets resolved receives an object that contains several values: status code, headers and data that will contain your data
I think problem is here
$scope.users = [];
angular.forEach(response.Users, function (value, key) {
$scope.users.push(value);
});
try change to
$scope.users = response.data.Users
or you can change to
$scope.users = [];
angular.forEach(response.data.Users, function (value, key) {
$scope.users.push(value);
});
angular.forEach(response.Users.User, function (value, key) {
$scope.users.push(value);
});
your array is nested so you have to call the array in the object

Create arrays from JavaScript objects

I have some data which looks like this:
{
"obj":
[
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
What I need to do is to create 2 arrays from it.
For example:
namelist[];
agelist[];
so the result would be:
namelist: ['name1', 'name2'];
agelist: [24, 17];
My question is, how can I do this?
var namelist = [];
var agelist = [];
for(var i in obj.obj){
namelist.push(obj.obj[i].name);
agelist.push(obj.obj[i].age);
}
console.log(namelist, agelist);
Is this what U wanted ?
var zz={
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
namelist.push(rec.name);
agelist.push(rec.age);
})
console.log(namelist,agelist)
You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
};
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
console.log(namelist);
console.log(agelist);
var arr = $.map(myObj, function(value, index) {
return [value];
});
console.log(arr);
if you are not using Jquery then:
var arr = Object.keys(myObj).map(function (key)
{ return obj[key];
});`
Make use of jquery map function or otherwise you can loop over the object and push it into array using javascript for loop and use the push() function. Refer Loop through an array in JavaScript
Jquery
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var name = $.map(data.obj, function(value, index) {
return value.name;
});
var age = $.map(data.obj, function(value, index) {
return value.age;
});
console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Javascript
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var names = [], ages=[];
data.obj.forEach(function(value, index) {
names.push(value.name);
ages.push(value.age);
});
console.log(names,ages);

retrieving data from an array, starting with specific nth item in AngularJs

Working on a project with Angular, and was curious if there is an 'angular-specific' method to acheive this.
I essentially want to retrieve data starting at a specific item in the array, like the 3rd.
You'll see in the html what I was curious if angular provides any type of method or filter.
html
<div ng-controller="bracketsController">
<div ng-repeat="bracket in brackets | limitTo: 2" class="bracket-container left" >
<div>{{bracket.brackets.single.contestant1}}</div>
<div>{{bracket.brackets.single.contestant2}}</div>
</div>
<div ng-repeat="bracket in brackets | limitTo: 2 SOME **Angular FILTER TO START AT 3**" class="bracket-container right" >
<div>{{bracket.brackets.single.contestant1}}</div>
<div>{{bracket.brackets.single.contestant2}}</div>
</div>
</div>
js
var bracketsapp = angular.module('bracketsApp', []);
bracketsapp.controller('bracketsController', function($scope){
$scope.brackets = [
{
"brackets": {
"single": {
"contestant1": "john doe",
"contestant2": "jane doe"
}
}
},
{
"brackets": {
"single": {
"contestant1": "john doe",
"contestant2": "jane doe"
}
}
},
{
"brackets": {
"single": {
"contestant1": "john doe",
"contestant2": "jane doe"
}
}
},
{
"brackets": {
"single": {
"contestant1": "john doe",
"contestant2": "jane doe"
}
}
},
{
"brackets": {
"single": {
"contestant1": "john doe",
"contestant2": "jane doe"
}
}
}
]
});
Thanks for any tips or suggestion.
You could just use the .slice method directly on the array:
<div ng-repeat="bracket in brackets.slice(3)" class="bracket-container right" >
Besides that though, there is a discussion they are having currently for the next version of angular to support this as a filter. You can follow along here: https://github.com/angular/angular.js/issues/5355
You can create you own filter, has mention here: Filter results 6 through 10 of 100 with ng-repeat in AngularJS
app.filter('slice', function() {
return function(arr, start, end) {
return (arr || []).slice(start, end);
};
});
<div ng-repeat="bracket in brackets | slice:3:2">{{item}}</div>

Dynamic Knockout table from JSON object

I was trying to populate a table with knockout integration. That takes data from Json.
JSON DATA
{
"info":[
{
"Name":"Noob Here",
"Major":"Language",
"Sex":"Male",
"English":"15",
"Japanese":"5",
"Calculus":"0",
"Geometry":"20"
},
{
"Name":"Noob Here",
"Major":"Calculus",
"Sex":"Female",
"English":"0.5",
"Japanese":"40",
"Calculus":"20",
"Geometry":"05"
}
]
}
I used knockout-mapping to dynamically map the data into the page. That has been added as Javascript in JS-bin. My script is in the sample's html page
$(document).ready(function () {
$("#div1").append("<tr><td data-bind='text: name'></td><td data-bind='text: major'></td><td data-bind='text: sex'></td><td><input data-bind='value: English' /></td><td><input data-bind='value: Japanese' /></td><td><input data-bind='value: Calculus' /></td><td><input data-bind='value: Geometry' /></td></tr>");
function loadData(fileName) {
var data = {
"info": [{
"Name": "Noob Here",
"Major": "Language",
"Sex": "Male",
"English": "15",
"Japanese": "5",
"Calculus": "0",
"Geometry": "20"
}, {
"Name": "Noob Here",
"Major": "Calculus",
"Sex": "Female",
"English": "0.5",
"Japanese": "40",
"Calculus": "20",
"Geometry": "05"
}]
}
return (data);
}
var dataFunction = function () {
this.Items = ko.observableArray([]);
};
var myFile = "Data";
var data = [];
var data1 = {
"info": [{
"Name": "Noob Here",
"Major": "Language",
"Sex": "Male",
"English": "15",
"Japanese": "5",
"Calculus": "0",
"Geometry": "20"
}, {
"Name": "Noob Here",
"Major": "Calculus",
"Sex": "Female",
"English": "0.5",
"Japanese": "40",
"Calculus": "20",
"Geometry": "05"
}]
}
if (data1 && data1.info) {
console.log(data1.info[0]);
$.each(data1.info[0], function (key, value) {
});
$.each(data1.info, function (index, element) {
data.push({
English: element.English,
Japanese: element.Japanese,
Calculus: element.Calculus,
Geometry: element.Geometry,
name: element.Name,
major: element.Major,
sex: element.Sex
});
});
dataFunction.prototype = function () {
var getAllItems = function () {
var self = this;
ko.mapping.fromJS(data, {}, self.Items);
};
var finalObj = {};
var info = [];
$.each(data1.info, function (i, v) {
var object = {};
$.each(v, function (i1, val1) {
if ($.isNumeric(val1)) {
object[i1] = val1
}
});
info.push(object);
});
finalObj['info'] = info;
console.log(finalObj);
return {
getAllItems: getAllItems
}
}();
var dataList = new dataFunction();
dataList.getAllItems();
ko.applyBindings(dataList);
}
});
I want to replace
data.push({
English: element.English,
Japanese: element.Japanese,
Calculus: element.Calculus,
Geometry: element.Geometry,
name: element.Name,
major: element.Major,
sex: element.Sex
});
Into a dynamic script so that what ever json data i add will be shown in the table format. Even if its column name or column number changes.
Does anyone know how to do it?
http://jsbin.com/ipeseq/1/
Assuming that the change in case for name, major and sex is not an actual requirement, you can just push the object.
data.push(element);
As is you're basically creating a copy of the element piece by piece and pushing that, why not just push the element itself?

Categories

Resources