Create array of objects in an object - Node.js - angularjs

In the below code, 'info' object has a description, quantity, value. How to give them as an array(Indo property). How to retrieve in angular code.
details.customsDetail.itemDetails = {
currency : "2000USD",
weight : "lbs",
info : {
description : "descr",
quantity : "2",
value : "124",
}
};

Do you mean , indo property as array of objects?
details.customsDetail.itemDetails = {
currency : "2000USD",
weight : "lbs",
info : [{ // How to give this in a array.
description : "descr",
quantity : "2",
value : "124",
}]
};

you can assign the object to a variable and later you can push it to an array.
var backUp = angular.copy($scope.details.customsDetail.itemDetails.info);
$scope.details.customsDetail.itemDetails.info = [];
$scope.details.customsDetail.itemDetails.info.push(backUp);
console.log($scope.details.customsDetail.itemDetails)
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.details = {"customsDetail":{"itemDetails":{}}};
$scope.details.customsDetail.itemDetails = {
currency : "2000USD",
weight : "lbs",
info : {// How to give this in a array.
description : "descr",
quantity : "2",
value : "124",
}
};
var backUp = angular.copy($scope.details.customsDetail.itemDetails.info);
$scope.details.customsDetail.itemDetails.info = [];
$scope.details.customsDetail.itemDetails.info.push(backUp);
console.log($scope.details.customsDetail.itemDetails)
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>

Related

Write an object to an .json file using angular?

I have an object like:
[
{
"text" : "Address of Bowlers game center in Chennai?",
"entities" : [
{
"entity" : "action",
"value" : "business"
},
{
"entity" : "intent",
"value" : "fetchItems"
},
{
"entity" : "bizCategory",
"value" : "bowling",
"start" : 11,
"end" : 30
},
{
"entity" : "wit$location",
"value" : "Chennai",
"start" : 34,
"end" : 40
}
]
},
{
.....more objects
}
]
Now I have to do some manipulation on this object and save the manipulated object into an .json file using angular js.
var originalObject = $http.get("data/chennai.json");
var manipuatedObject; // this is the manipulated object i get after applying some changes on originatalObject.
Now how can I save this manipuatedObject into an json file.
Try this:
function saveText(text, filename){
var a = document.createElement('a');
a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text));
a.setAttribute('download', filename);
a.click()
}
So a possible use might be:
var obj = {a: "Hello", b: "World");
saveText( JSON.stringify(obj), "filename.json" );

es6 Loop through object array and aggregate unique values from key pair (cleanest way)

What's the cleanest and es6 native (if possible) way to loop through a object array to grab each unique value. Example would like this :
[{
"name" : "joe",
},
,{
"name" : "jean",
},
{
"name" : "joe",
},
{
"name" : "joe",
},
{
"name" : "mike",
}]
and in my results I want to see only : joe, jean, mike (only unique values, no dupes)
Since you mentioned ES6, it seems like a Set object would be what you want since it will do the uniqueness part for you and should do so fairly efficiently:
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
let uniqueNames = Array.from(new Set(objs.map(item => item.name)));
console.log(uniqueNames);
Run this snippet to see the results.
a = [{name:"joe"},{name:"jean"},{name:"joe"},{name:"joe"},{name:"mike"}]
console.log(_.uniq(_.map(a, 'name'))) // Lodash 0.1.0
console.log([...new Set(a.map(o => o.name))]) // ES6
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.4/lodash.min.js"></script>
var objs = [{"name" : "joe"},{"name" : "jean"},{"name" : "joe"},{"name" : "joe"},{"name" : "mike"}];
var uniqueNames = objs.map( obj => obj.name )
.filter( (name, idx, arr) => { return arr.indexOf(name) === idx; } );
The .map extracts an array of the name values, and the .filter returns only the unique elements (first instances only).

AngularJS orderby sorts number and dates treating them as string

I need to develop a table in angular js to show a third party data (and hence data cannot be changed).
Data to be shown is completely dynamic in that number or sequence of columns can change anytime.
The value to be displayed may be a number or a string or a date, which is governed by the third party data.
I need to sort table on clicking on any of the headers
I am aware of some techniques like using | number filter etc, but it does not seem to work in this dynamic environment
Hence I need to make my table as completely dynamic.
However I am facing issues in using order by as it sorts even numbers and dates treating them as string.
<table>
<td ng-repeat="key in keys(Header[0])" ng-click="maintainOrder(key)" >
<span>{{Header[0][key]}}</span>
</td>
<tr ng-repeat="singleRow in data | orderBy:orderByCriteria:reverseSort" >
<td ng-repeat="key in keys(data[0])" >
{{singleRow[key]}}
</td>
</tr>
</table>
$scope.maintainOrder = function(key)
{
$scope.orderByCriteria = key;
$scope.reverseSort = ! $scope.reverseSort;
};
$scope.keys = function(obj){
console.log((Object.keys(obj)));
return obj? Object.keys(obj) : [];
};
$scope.data= [
{
"quantity" : "85",
"type" : "mango",
"expiryDate" : "15/09/2015"
},
{
"quantity" : "9",
"type" : "orange",
"expiryDate" : "5/07/2015"
},
{
"quantity" : "66",
"type" : "apple",
"expiryDate" : "25/09/2015"
},
{
"quantity" : "95",
"type" : "mango",
"expiryDate" : "31/08/2015"
}
];
$scope.Header= [
{
"quantity" : "Qty ",
"type" : "Type",
"expiryDate" : "Expiry_Date"
}];
I have included a fiddle for the same:
fiddle link
You can create your own custom sort filter, and use the angular built-in functions angular.isNumber, angular.isDate, angular.isString
An example of a custom filter is here: http://jsfiddle.net/av1mLpqx/1/
In your custom filter, use a custom sort function like this:
array.sort(function (a, b) {
if (angular.isNumber(a) && angular.isNumber(b)) {
return a - b;
}
else if (angular.isDate(a) && angular.isDate(b)) {
return a.getTime() - b.getTime();
}
else if (angular.isString(a) && angular.isString(b)) {
return a.localeCompare(b);
}
else {
console.log("types unknown");
return 0;
}
}

AngularJS ng-class check if nested key/value pair exists and then add value as class

So, I have this nested array which I can't modify the structure of. I want to check if a key/value pair exists and if it does, add a corresponding class to the element in question.
I have been trying to use a variation of the expression:
ng-class="{ 'active' : data.indexOf('"name":"john"') >= 0 }"
However my expression is a bit more complicated and I'm afraid it's too much to use just like that. There's also the problem of using more than two level nested quotes.
Here's a fiddle using an array with a similar structure to what I'm working with:
http://jsfiddle.net/5tvmL2Lg/2/
HTML:
<body ng-app="myModule">
<div ng-controller="myController">
<div ng-repeat="hero in heroes">
<div ng-class="{ 'weight-\'hero.stats.indexOf('\'type\':\'weight\'').value\'' : hero.stats.indexOf('\'type\':\'weight\'') >= 0 }">
hello
</div>
</div>
</div>
</body>
JS:
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', function($scope) {
$scope.heroes = [{
"firstname" : "clark",
"lastname" : "kent",
"stats" : [
{
"type" : "height",
"value" : "6'2"
},
{
"type" : "weight",
"value" : 220
},
{
"type" : "hair",
"value" : "brown"
}
]},
{
"firstname" : "bruce",
"lastname" : "wayne",
"stats" : [
{
"type" : "height",
"value" : "6'1"
},
{
"type" : "hair",
"value" : "black"
}
]},
{
"firstname" : "peter",
"lastname" : "parker",
"stats" : [
{
"type" : "height",
"value" : "5'11"
},
{
"type" : "weight",
"value" : 180
},
{
"type" : "hair",
"value" : "auburn"
}
]}];
}]);
In the end the goal would be to add a class named for example "weight-220" for the "clark kent" div, no class for the "bruce wayne" div, and "weight-180" for the peter parker div.
I know my problem is convoluted but any help would be greatly appreciated... :)
You don't need to add all your code logic into your ng-class. You can make it more complex (to check for the deeply-nested objects) by using a function that returns a string:
<div ng-repeat="hero in heroes">
<div ng-class="ClassBuilder(hero)">
hello
</div>
</div>
In your controller, add this function:
$scope.ClassBuilder = function(hero) {
for (var i = 0; i < hero.stats.length; i++) {
if (hero.stats[i].type == "weight") {
return "weight-" + hero.stats[i].value;
}
}
}
This will receive the hero object from each ng-repeat and check if the weight type exists. If so, it will use the corresponding value to return a string in your requested format, for example: "weight-220". Otherwise, it will return nothing and no class will be applied to that <div>.

Firebase angular many to many relation query

I have a fairly simple json structure of groups and people and I am struggling to get/read a list of the group names for each person from firebase. This is what I tried. I spent a couple of days debugging unsuccessfully. Help much appreciated.
JSON:
{
"groups" : {
"one" : {
"members" : {
"-KLxjv9OnQB2l5Ohr-7I" : true
},
"name" : "group alpha"
},
"two" : {
"members" : {
"-KM4oXjftRZZ5DXYt4B2" : true
},
"name" : "group beta"
},
"three" : {
"members" : {
"-KM4oXjftRZZ5DXYt4B2" : true
},
"name" : "group gamma"
}
},
"persons" : {
"-KLxjv9OnQB2l5Ohr-7I" : {
"groups" : {
"one" : true
},
"personName" : "name1",
"personTitle" : "title1"
},
"-KM4oXjftRZZ5DXYt4B2" : {
"groups" : {
"two" : true
},
"personName" : "name2",
"personTitle" : "title2"
}
}
}
APP.JS:
$scope.personsGroup = function(personObj){
var baseRef = new Firebase("https://un-cms-13264.firebaseio.com/");
var personsRef = baseRef.child('persons');
var groupsRef = baseRef.child('groups');
var res=[];
for(var i=0;i<Object.keys(personObj.groups).length;i++){
var groupKey=Object.keys(personObj.groups)[i]
res.push($firebaseArray(groupsRef.child(groupKey)));
};
return res;
}
HTML:
<div class="row" ng-repeat="person in persons">
<div class="col-lg-3"></div>
<div class="col-lg-3">{{person.personName}}</div>
<div class="col-lg-3"></div>
<div class="col-lg-3 groupsList">
<ul><li ng-repeat="group in personsGroup(person)">{{group.name}}</li></ul>
</div>
</div>
The best way would be to attach $firebaseArray to a $scope variable:
var ref = new Firebase("https://un-cms-13264.firebaseio.com/").child("persons").child(some-person).child("groups");
$scope.personsGroup = $firebaseArray(ref);
// When loaded
$scope.personsGroup.$loaded(function(data) {
// can do something
}, function(error) {
// error
});
How you determine some-person is up to you. You could query the persons tree and store all the persons or store it inside an array or object.
<ul>
<li ng-repeat="(key, value) in personsGroup">{{ key }}</li>
</ul>
I would not advise personGroup(person) because $firebaseArray is an asynchronous call and I feel like it could be real jumpy. Be smart with it, you could also just get the entire persons tree in one call if you wanted:
var ref = new Firebase("https://un-cms-13264.firebaseio.com/").child("persons");
$scope.persons = $firebaseArray(ref);
And do some iterating of that.

Resources