I have this list i wanted to display on ng-table.
$scope.list = [
{
"moduleId": 1,
"name": "Perancangan",
"level": 0,
"childs": [
{
"moduleId": 12,
"name": "Perancangan Sektor",
"level": 1,
"childs": [],
"links": [
{
"rel": "self",
"href": "http://103.8.160.34/mrf/modules/1"
}
]
}
]
},
{
"moduleId": 2,
"name": "Pengurusan Pengguna dan Peranan",
"level": 0,
"childs": [
{
"moduleId": 17,
"name": "Pengurusan Pengguna",
"level": 1,
"childs": [],
"links": []
},
{
"moduleId": 18,
"name": "Operasi Peranan",
"level": 1,
"childs": [],
"links": []
}
],
"links": [
{
"rel": "self",
"href": "http://103.8.160.34/mrf/modules/2"
}
]
}
];
I wanted the list.childs to be the rows in the table with the list.name as grouping, i'd used ng-repeat to but doesn't work. The most i could do is display it as td. What im looking at is
Perancangan (header)
Perancangan Sektor
Pengurusan Pengguna dan Peranan
Here is the plunker
http://plnkr.co/edit/77t5id3WOmbl2GSqYKh2?p=preview
There seems to be at least two ways you could accomplish this. The first might be more simple but skirts the question you posed. Massage the list[] into a flattened and simplified array tailored for this table's view. You would then ng-repeat over that array.
That is really a dodge though and completely avoids your question. More directly to your question you could try to use nested ng-repeat's but those are pretty tricky. See: http://vanderwijk.info/blog/nesting-ng-repeat-start/
Finally, the approach that seems to best address you're question in both intent and spirit is to use a custom filter. I've written an example fiddle that should demonstrate the idea.
app.filter('flatten', function() {
// Because this filter is to be used for an ng-repeat the filter function
// must return a function which accepts an entire list and then returns
// a list of filtered items.
return function(listItems) {
var i,j;
var item, child;
var newItem;
var flatList = [];
// Begin a loop over the entire list of items provided by ng-repeat
for (i=0; i<listItems.length; i++) {
var item = listItems[i];
// Construct a new object which contains just the information needed
// to display the table in the desired way. This means we just extract
// the list item's name and level properties
newItem = {};
newItem.name = item.name.toUpperCase();
newItem.level = item.level;
// Push the level 0 item onto the flattened array
flatList.push(newItem);
// Now loop over the children. Note that this could be recursive
// but the example you provided only had children and no grandchildren
for (j=0; j<item.childs.length; j++) {
child = item.childs[j];
// Again create a new object for the child's data to display in
// the table. It also has just the name and level.
newItem = {};
newItem.name = child.name;
newItem.level = child.level;
flatList.push(newItem);
}
}
// Return the newly generated array that contains the data which ng-repeat
// will iterate over.
return flatList;
};
});
Related
I want to loop through 600+ array items in an object and find one particular item based on certain criteria. The array in the object is called "operations" and its items are arrays themselves.
My goal is to get the index of operation's array item which has the deeply nested string "Go".
In the sample below this would be the first element. My problem is that I can check if an array element contains "call" and "draw" but I don't know how to test for the nested dictionary "foobar". I only have basic JavaScript available, no special libraries.
let json = {
"head": {},
"operations": [
[
"call",
"w40",
"draw",
{
"parent": "w39",
"style": [
"PUSH"
],
"index": 0,
"text": "Modify"
}
],
[
"call",
"w83.gc",
"draw",
{
"foobar": [
["beginPath"],
[
"rect",
0,
0,
245,
80
],
["fill"],
[
"fillText",
"Go",
123,
24
],
[
"drawImage",
"rwt-resources/c8af.png",
]
]
}
],
[
"create",
"w39",
"rwt.widgets.Menu",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
],
[
"call",
"w39",
"draw",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
]
]
};
let index = "";
let operationList = json.operations;
for (i = 0; i < operationList.length; i++) {
if (operationList[i].includes('call') && operationList[i].includes('draw')) //missing another check if the dictionary "foobar" exists in this element )
{
index = i;
}
}
document.write(index)
I'll preface by saying that this data structure is going to be tough to manage in general. I would suggest a scheme for where an operation is an object with well defined properties, rather than just an "array of stuff".
That said, you can use recursion to search the array.
If any value in the array is another array, continue with the next level of recursion
If any value is an object, search its values
const isPlainObject = require('is-plain-object');
const containsTerm = (value, term) => {
// if value is an object, search its values
if (isPlainObject(value)) {
value = Object.values(value);
}
// if value is an array, search within it
if (Array.isArray(value)) {
return value.find((element) => {
return containsTerm(element, term);
});
}
// otherwise, value is a primitive, so check if it matches
return value === term;
};
const index = object.operations.findIndex((operation) => {
return containsTerm(operation, 'Go');
});
Is there any way to compare two arrays and push to an empty array if the condition is met?
Say I have an array of objects. I need to loop through the array of objects, get a ID; then compare that ID to a different array. Then if they match push a value in that array to an empty array?
Array 1:
[{
"addon_service": {
"id": "f6f28cb5-78ad-4ec7-896d-16462b8202fd",
"name": "papertrail"
},
"app": {
"id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2",
"name": "mdda-mobiledocdelivery-stg"
}
}]
Array 2
[{
"app": {
"id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2"
},
"stage": "staging",
}]
I need to match Array 1 app.ID to Array 2 app.id. If they match check what stage the app is in (staging, development or production). Then push Array 1 addon_service.name to either a staging develpment or
production array depending on what stage the application is in. I'm thinking its simple just cant get my head around it.
I think this is a poorly worded question.
You could use a hash table for lookup and for the stage and use an object for collecting the matches.
var array1 = [{ "addon_service": { "id": "f6f28cb5-78ad-4ec7-896d-16462b8202fd", "name": "papertrail" }, "app": { "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2", "name": "mdda-mobiledocdelivery-stg" } }],
array2 = [{ "app": { "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2" }, "stage": "staging", }],
hash = Object.create(null),
result = {};
array2.forEach(function (a) {
hash[a.app.id] = a.stage;
});
array1.forEach(function (a) {
if (hash[a.app.id]) {
result[hash[a.app.id]] = result[hash[a.app.id]] || [];
result[hash[a.app.id]].push(a.addon_service.name);
}
})
console.log(result);
I think this will do it.
$.each(app1, function(key, value){
$.each(app2, function(k, v){
if(value.app.id == v.app.id){// find apps with the same `id`
if(v[v.stage]){// check if the `stage` array already exists.
v[v.stage].push(value.addon_service)
}else{
v[v.stage] = [value.addon_service];
}
}
});
});
Where app1 is the first array in your question and app2 the second one.
I'm trying to create a JSON array to send it to my web service. This is how my json should look like:
[{
"tipus": 1,
"proveidor": 3,
"atributs": {
"atribut":{
"id": 1,
"valor": 8
},
"atribut":{
"id": 2,
"valor": 500
}
}
}]
So, I have two general values "tipus" and "proveidor" and multiple "atributs" each "atribut" is composed with "id" and "valor".
When I construct the json I get this instead of what I want:
[
2:{
"tipus": 1,
"proveidor": 3,
1:{
"id": 1,
"valor": 8
},
0:{
"id": 2,
"valor": 500
}
}]
This is how I'm building the json:
// For every founded in $scope.atrb i need to create an 'atribut' element into my json
$scope.a = [];
var key;
for(key in $scope.atrb){
var newField = {
"idatributs_actiu": $scope.atrb[key].idatributs_actiu,
"nomAtribut": $scope.atrb[key].nomAtribut,
"valor": $scope.atrb[key].valor,
"idActiu": $routeParams.idTipusActiu,
"value": "",
"ordre": $scope.atrb[key].ordre,
"idatributs_generics": $scope.atrb[key].idatributs_generics
};
$scope.a.push(newField);
}
$scope.f = $scope.a;
});
var generics = {
"nom": $scope.nom,
"tipus": $routeParams.idTipusActiu,
"proveidor": $scope.proveidor.id
};
$scope.a.push(generics);
It's my first project with angular and I'm not sure if I'm building the json appropriately, basically i use an array to build a json but I don't know how to nested it 'atribut' inside 'atributs'.
The main idea is to read the 'generics' atributes and then loop through 'atributs' and read all 'atribut' element getting the properties.
Regards
Like S4beR and Kevin B told me, I just need to do an JS array. This is in my controller:
var obj = { generics: g, atributs: $scope.a };
g: it's an object with the generic properties
$scope.a: this is an array with 'atribut' objects which contais all
the properties I need save to.
I have 2 array objects in Angular JS that I wish to merge (overlap/combine) the matching ones.
For example, the Array 1 is like this:
[
{"id":1,"name":"Adam"},
{"id":2,"name":"Smith"},
{"id":3,"name":"Eve"},
{"id":4,"name":"Gary"},
]
Array 2 is like this:
[
{"id":1,"name":"Adam", "checked":true},
{"id":3,"name":"Eve", "checked":true},
]
I want the resulting array after merging to become this:
[
{"id":1,"name":"Adam", "checked":true},
{"id":2,"name":"Smith"},
{"id":3,"name":"Eve", "checked":true},
{"id":4,"name":"Gary"},
]
Is that possible? I have tried angular's array_merge and array_extend like this:
angular.merge([], $scope.array1, $scope.array2);
angular.extend([], $scope.array1, $scope.array2);
But the above method overlap the first 2 objects in array and doesn't merge them based on matching data. Is having a foreach loop the only solution for this?
Can someone guide me here please?
Not sure if this find of merge is supported by AngularJS. I've made a snippet which does exactly the same:
function merge(array1, array2) {
var ids = [];
var merge_obj = [];
array1.map(function(ele) {
if (!(ids.indexOf(ele.id) > -1)) {
ids.push(ele.id);
merge_obj.push(ele);
}
});
array2.map(function(ele) {
var index = ids.indexOf(ele.id);
if (!( index > -1)) {
ids.push(ele.id);
merge_obj.push(ele);
}else{
merge_obj[index] = ele;
}
});
console.log(merge_obj);
}
var array1 = [{
"id": 1,
"name": "Adam"
}, {
"id": 2,
"name": "Smith"
}, {
"id": 3,
"name": "Eve"
}, {
"id": 4,
"name": "Gary"
}, ]
var array2 = [{
"id": 1,
"name": "Adam",
"checked": true
}, {
"id": 3,
"name": "Eve",
"checked": true
}, ];
merge(array1, array2);
Genuinely, extend in Angular works with object instead of array. But we can do small trick in your case. Here is another solution.
// a1, a2 is your arrays
// This is to convert array to object with key is id and value is the array item itself
var a1_ = a1.reduce(function(obj, value) {
obj[value.id] = value;
return obj;
}, {});
var a2_ = a2.reduce(function(obj, value) {
obj[value.id] = value;
return obj;
}, {});
// Then use extend with those two converted objects
var result = angular.extend([], a1_, a2_).splice(1)
Notes:
For compatibility, reduce may not work.
The after array will replace the previous one. This is because of implementation of extend in Angular.
Still this problem Angular.js more complex conditional loops but I felt that the answer to the question as it was asked was right so I accepted it.
So let me elaborate more than I did in the original question.
I'm trying to get this
<h3>11.4.2013</h3>
<ul>
<li>oofrab | 4 | 11.4.2013 14:55 <button>remove</button></li>
<li>raboof | 3 | 11.4.2013 13:35 <button>remove</button></li>
</ul>
<h3>10.4.2013</h3>
<ul>
<li>barfoo | 2 | 10.4.2013 18:10 <button>remove</button></li>
<li>foobar | 1 | 10.4.2013 12:55 <button>remove</button></li>
</ul>
from this data structure
[
{
"id": 4,
"name": "oofrab",
"date": "2013-11-04 14:55:00"
},
{
"id": 3,
"name": "raboof",
"date": "2013-11-04 13:55:00"
},
{
"id": 2,
"name": "barfoo",
"date": "2013-10-04 18:10:00"
},
{
"id": 1,
"name": "foobar",
"date": "2013-10-04 12:55:00"
}
]
Basically the only extra thing over the standard ng-repeat I want to add are those headings. And I simply can't believe I'd have to go thru so many problems by adding them.
This is what I ended up with using the answer I got in the first question http://plnkr.co/edit/Zl5EcsiXXV92d3VH9Hqk?p=preview
Note that there can realistically be up to 400 entries. And I need to be able to add/remove/edit entries on the fly
What the example on plunker is doing is this:
iterating thru the original data creating a new data structure looking like this
{
"2013-10-05": [
{
"id": 4,
"name": "oofrab",
"date": "2013-10-05 14:55:00",
"_orig_index": 0
},
{
"id": 3,
"name": "raboof",
"date": "2013-10-05 13:55:00",
"_orig_index": 1
}
],
"2013-10-04": [
{
"id": 2,
"name": "barfoo",
"date": "2013-10-04 18:10:00",
"_orig_index": 2
},
{
"id": 1,
"name": "foobar",
"date": "2013-10-04 12:55:00",
"_orig_index": 3
}
]
}
allowing me to then get the result I wanted by doing this
<div ng-repeat="(date,subItems) in itemDateMap">
<h3>{{date}}</h3>
<ul>
<li ng-repeat="item in subItems">
{{item.name}} | {{item.id}} | {{item.date}}
<button type="button" ng-click="removeItem(item._orig_index)">x</button>
</li>
</ul>
</div>
Great. But it comes with a cost of shizzload of problems. Everytime a new item is added I have to rebuild the itemDateMap, everytime an item is deleted I have to rebuild the itemDateMap, everytime date is changed, I have to rebuild the itemDateMap. When I want to remove an item, I have to first get index of its original reference. And everytime itemDateMap is rebuilt, the whole thing is re-rendered. And it can't be sorted, as it's an object rather than an array.
When there's a couple of hundred of entries, it also becomes really, really slow. I read somewhere that ng-repeat is quite intelligent, watching values, moving nods in dom rather than re-rendering everything and stuff, but it surely doesn't work this way when I rebuild the whole structure.
This can't be right, all this hassle to do a very, very simple thing..
What should I do?
This is my suggestion - just work with one structure, and only expose one structure to the scope (the map). And create a function to add an array of items to the map, and a function that transforms the map into an array (I assume you need this array for server communication or something).
var toKey=function(item){
return moment(item.date).format("YYYY-MM-DD");
}
$scope.itemDateMap = {};
$scope.addItemToDateMap=function(item){
var key = toKey(item);
if(!$scope.itemDateMap[key]){
$scope.itemDateMap[key] = [];
}
$scope.itemDateMap[key].push(item);
}
$scope.removeItemFromDateMap=function(item){
var key = toKey(item), subitems = $scope.itemDateMap[key];
var index = subitems.indexOf(item);
subitems.splice(index,1);
if(subitems.length === 0){
delete $scope.itemDateMap[key];
}
}
var addArrayToMap = function(items){
for(var i=0; i<items.length; i++){
var item = items[i];
$scope.addItemToDateMap(item);
}
};
$scope.mapToArray = function(){
var items = [];
for(var key in $scope.itemDateMap){
var subitems = $scope.itemDateMap[key];
for(var j=0;j<subitems.length;j++){
var item = subitems[j];
items.push(item);
}
}
return items;
}
I've updated your plnkr with my suggestion. I think it performs quite well.
Oh - I just noticed you want it sorted - I don't have time to update my example, but it is not very complicated. Use this structure instead (array with objects with arrays, instead of object with array) - this way you can use the orderBy:'date' on the root array:
[
{
date:"2013-10-05",
items: [
{
"id": 4,
"name": "oofrab",
"date": "2013-10-05 14:55:00"
},
{
"id": 3,
"name": "raboof",
"date": "2013-10-05 13:55:00"
}
]
},
{
date:"2013-10-04",
items: [
{
"id": 2,
"name": "barfoo",
"date": "2013-10-04 18:10:00"
},
{
"id": 1,
"name": "foobar",
"date": "2013-10-04 12:55:00"
}
]
}
]