Access array values - AngularJs - angularjs

Hello I have array of friends this.venner
also I have array called this.convensations and output is like this.venner,
but id here is called partner_id (partner_id output is 54312, 54345, 54346 )
now I want compare if this.convensation partner_id and this.venner id if is same
something like this:
if (this.convensation in this.venner) {
//do something
} else {
// do something
}

You can use the Array.prototype.some() method.
If you wrap that in it's own checkExistsInArray function...
function checkExistsInArray(arr, compareObj){
return arr.some(function(obj){
return compareObj[Object.keys(compareObj)] === obj[Object.keys(compareObj)];
});
}
... then you should be able to use that for both arrays by passing in a custom compare object.
var friendExists = checkExistsInArray(this.venner, { id: this.friend });
var conversationExists = checkExistsInArray(this.conversations, { partner_id: this.friend });
Side Note : As others have pointed out, there are libraries out there to readily do this sort of thing. Two of the main players I'm aware of are Underscore.js and Lodash. Even if you choose not to use them, it can sometimes be helpful to see how they work under the hood when looking for a little bit of inspiration.

You can use filter,
var result = this.venner.filter(t=>t.id === '54312');
if (result.length >0) {
//do something
} else {
// do something
}

Simply you can solve this using Undescore.js _.find function
if (.find(this.friend, {"id":this.venner) {
//do something
} else {
// do something
}

Related

Getting elements from array based on property values (AngularJS)

I have an array of players, each player is an object that has a number of properties, one is "goals".
var players = [
{
"id":"4634",
"name":"A. Turan",
"number":"0",
"age":"28",
"position":"M",
"goals":"1"
},
{
"id":"155410",
"name":"H. Çalhano?lu",
"number":"0",
"age":"21",
"position":"A",
"goals":"0"
},
{
"id":"4788",
"name":"B. Y?lmaz",
"number":"0",
"age":"30",
"position":"A",
"goals":"2",
}
]
I've written a function to cycle through the array and push every element that has more than '0' goals to an array, topScorers. Like so:
$scope.topScorerSearch = function() {
var topScorers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o.goals > 0) {
topScorers.push(o)
}
});
return topScorers;
}
With the function called as {{topScorerSearch()}}.
This returns only players who have scored. Perfect.
However, I want to run this on other properties, which will result in a lot of repetitious code. How can I make this a general purpose function that can be executed on different properties?
I tried including the 'prop' parameter, but it didn't work:
$scope.topScorerSearch = function(prop) {
var topScorers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o.prop > 0) {
topScorers.push(o)
}
});
return topScorers;
}
...and called the function like this:
{{topScorerSearch(goals)}}
Why doesn't this work? Where am I going wrong?
I believe the issue is that prop will not resolve to goals because goals is being treated as a variable with a null or undefined value, making prop null or undefined.
If you use the alternative way of accessing object properties object["property"] and use the function {{topScorers("goals")}} it should work out.

iterate each object in array and populate each element of the array with result. asynchronously

I need help with array asynchronous iterate functionality. I working with node-opcua library in nodejs. There is function session.browse(nodeId, result)
Right now code looks like:
NodesTree = {
"NodesTree":{
"name":"SYM:",
"subf":[]
}
};
the_session.browse("ns=1;s=SYM:", function(err, browse_result){
if(!err) {
var buf = [];
browse_result[0].references.forEach(function(reference) {
if (reference1.browseName.namespaceIndex > 1) {
buf.push(reference);
}
});
NodesTree.subf = buf;
}
});
In result I get references of SYM: folder example:
[{"referenceTypeId":"ns=0;i=35","isForward":true,"nodeId":"ns=6;s=S71500ET200MP station_1","browseName":{"namespaceIndex":6,"name":"S71500ET200MP station_1"},"displayName":{"text":"S71500ET200MP station_1","locale":"en"},"nodeClass":"Object","typeDefinition":"ns=0;i=61"}]
I have Nodes structure in opc like this:
->SYM:
-->PLC
--->PLC_name
---->global_tag <variable>
---->global_tag1 <variable>
---->block
------>blok_tag1 <variable>
------>block_tag2 <variable>
Task is make one complete JSON object as tree for further use.
Logic is that: for each element in the references array get nodeId value and browse for references of the element and assign as element.subf = reference.
Final result something like:
NodesTree = {
"NodesTree":{
"name":"SYM:",
"subf":[
{attributes of PCL structure got by **browse**() + subf:[{ attributes of PLC_name by browse(), subf:
[{....and here again attributes and subf] }, {if no subf just assign subf; [] }]
]
}
};
So need call session.browse() for each reference and all finally bind to one object.
I tried to use Async library each and map in series functions to solve all that, but get nothing wise in result. May be there some smart solution can be found by Stack overflow community. Please help.
I am not familiar with node-opcua but assume that session.browse() is also async. Then something like this might work?
var async = require('async');
async.map(buf,
function(reference, callback) {
session.browse(reference.nodeId, function (err, result) {
callback(err, result);
});
}, function(err, results) {
// results is now an array of all single results
NodesTree.subf = results;
});

Get form array data from Busboy

How do I get array form data using busboy?
In route:
req.busboy.on('field', function(fieldname, val){
//fieldname is string, expecting array
//'bunnies[gray]', etc...
});
And my view:
form(method="post" action="/post/path" enctype="multipart/form-data")
input(name="bunnies[gray]")
input(name="bunnies[white]")
input(name="bunnies[black]")
input(name="bunnies[brown]")
input(name="bunnies[purple]")
So busboy isn't stupid -- multipart/form-data does not by default support arrays in the same way as a JSON body does.
Requests with arrayName[n] as field names will not be parsed as arrays by busboy alone -- such a payload will have still have to be parsed manually.
One can manually parse these array values using one of these other answers...
... but if manually parsing arrays is undesired, one may consider using co-busboy instead using this option:
autoFields: true
The question is rather old, but in case someone else stumbles upon this problem, here's what I did:
var arr = new Array();
req.pipe(req.busboy);
req.busboy.on('field', function(key, value) {
if(key === 'array_name[]') {
arr.push(value);
}
});
req.busboy.on('finish', function() {
console.log(arr);
});
Question if 5 years old but it gave me a hint. I am coming from PHP background and didn't realize that Busboy is this stupid, so if you want to process array of fields, you need to actually process them like this:
busboy.on('field', (fieldname, val) => {
if (fieldname.indexOf('[]') !== -1) {
let fn = fieldname.replace('[]', '');
if (typeof req.body[fn] === 'undefined') {
req.body[fn] = [];
}
req.body[fn].push(val);
} else {
req.body[fieldname] = val;
}
});
Hope to save someone else a few hours of debugging ...

run values from array into "gift_id":

I'm learning actionscript 3 and trying to get values from the array to be passed one after another into "gift_id": , and basically reward gifts. I am not totally sure if it could be done like this or the best way to achieve it. Any advice would be appreciated.
public function userGift(): Object {
var gift_id: Array = [2373, 9383, 4444, 4557, 8737];
return {
"change_type": "accepted",
"gift_id": ,
};
}
Function can only return single object, so I don't think this is a good way to do it. If you want to reuse it, you can call it multiple times if you pass id as a parameter.
var giftsArray:Array = [];
for each(var id:int in gift_id) {
giftsArray.push( userGift(id) );
}
//You should have an Array full of gift objects.
trace(giftsArray.length);
public function userGift(id:int):Object {
return {
"change_type": "accepted",
"gift_id": id,
};
}

Backbone - trying to make a filter on a collection with nested object

i'm trying to filter a collection which has models with some nested object. Unfortunately, my result are always empty.
So my models returned in the collection are build like this:
My goal is simple:
I have a view with a list of tag and a content view with all the questions. When a user click on tag, for example, "c#", i want to filter my collection to just return questions with tag "c#"
Before i was doing a fetch on my server and it was working fine, but it was not optimize.
I already have a collection with all the questions so why make a new call, a filter is a better solution i think.
But i didn't succeded with my filter and i don't know if it's possible to do. For now i put my filter in my router because it's more easy to test.
i can't make a filter like this because i have an array of object
getQuestionsByTags: function(query) {
var test = this.questionsCollection.filter(function(model) {
return model.attributes.tags.name == query;
})
console.log('result');
console.log(test);
},
So i was thinking to make a loop but my result is always an empty array.
getQuestionsByTags: function(query) {
var test = this.questionsCollection.filter(function(model) {
_.each(model.attributes.tags, function(tag) {
return tag.name == query;
})
})
console.log('result');
console.log(test);
},
It's maybe simple, but i don't know what to do.
Thanks in advance :)
i've just found a solution that work.
getQuestionsByTags: function(query) {
var flag;
var test2 = this.questionsCollection.filter(function(model) {
flag = false;
_.each(model.attributes.tags, function(tag) {
if(tag.name == query) {
flag = true;
}
})
if(flag) {
return model.attributes;
}
})
console.log('result');
console.log(test2);
},
i put a flag. If he turn true inside the loop, the model has this tag so i return it.
I think it's not very conventional, so if someone have another solution, feel free to post it :)

Resources