I have the following code to get the order of elements. But instead of getting an array in the order of the elements, it's alphabetical.
function gatherTreeIds( $parent ){
var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
GatheredIds[ this.title ] = 'someValue';
});
return GatheredIds;
}
<div id="Wrap">
<div class="nt_row" title="AAA"></div>
<div class="nt_row" title="CCC"></div>
<div class="nt_row" title="BBB"></div>
</div>
Here is my jsFiddle example (check console for result). It gives me ['AAA','BBB','CCC'] instead of the desired ['AAA','CCC','BBB'].
Important! This has to get recursive. It is not at this moment to simplify the problem.
You're confusing the two concepts of arrays and hashes. Arrays have order, while hashes have named keys, you can't have both in a data single structure.
With an array you would use:
var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
GatheredIds.push('someValue');
});
return GatheredIds;
If you want to record the item title, you can use an array of hashes:
var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
GatheredIds.push({value: 'someValue', title: this.title);
});
return GatheredIds;
This happens because you store titles as object properties. In your example GatheredIds is not array, this is an object.
Objects in JavaScript do not have order (opposite to PHP's map-arrays). If you need to follow the order, you should use arrays instead.
One possible solution:
function gatherTreeIds( $parent ){
return $parent.children('div.nt_row').map(function() {
return {
title: this.title,
value: 'someValue'
};
}).get();
}
DEMO: http://jsfiddle.net/FmyBb/4/
Related
I am trying to take some some objects from an original object into an array variable.
console.log("news len", news["articles"].length); // this comes out to 9
for(var a in news["articles"]) {
var results = [];
results.push({
title:news["articles"][a]["title"],
subtitle: news["articles"][a]["description"],
item_url:news["articles"][a]["title"],
image_url:news["articles"][a]["urlToImage"],
});
}
console.log("results len",results.length); //only contains one entry
Is there another way to accomplish this, and if not what am I doing wrong?
Using Node js if that helps any.
You could use map directly and return an object in the callback for a new array
var results = news.articles.map(function (a) {
return {
title: a.title,
subtitle: a.description,
item_url: a.title,
image_url: a.urlToImage
};
};
The main problem is that each iteration of your loop re-sets results to an empty array:
var results=[];
If you move that statement before your loop, you will get something closer to what you want.
That said, it looks like news["articles"] already is an array, so you can probably just use Array.prototype.map?
var results = [];
news["articles"].map(function(val,idx){
results.push({
title: val["title"],
//etc
}
});
I have array of objects named tickets and I want to pick some specific objects from tickets like number,desc and state and assign them to new array of objects say myarr. I'm writing the below code but it says number is undefined. What am I doing wrong ?
$scope.myarr=[{
number:"",
desc:"",
state:""
}
];
for(var i=0;i<$scope.tickets.length;i++){
$scope.myarr[i].number=$scope.tickets[i].number;
$scope.myarr[i].desc=$scope.tickets[i].short_description;
$scope.myarr[i].state=$scope.tickets[i].state;
}
You need do something like this.
$scope.myarr=[];
for(var i=0;i<$scope.tickets.length;i++){
//Your Conditions
var object={
"number":$scope.tickets[i].number,
"desc" :$scope.tickets[i].short_description,
"state":$scope.tickets[i].state
}
$scope.myarr.push(object);
}
$scope.myarr = [];
angular.forEach($scope.tickets, function(ticket) {
this.push({number:ticket.number, state: ticket.state});
}, $scope.myarr);
If you don't need to support IE < 9, there is a handy function called map which is useful in this case
$scope.myarr = $scope.tickets.map(function(ticket) {
// return the element to be inserted in the new array
return {
number: ticket.number,
desc: ticket.short_description,
state: ticket.state
};
});
I've been struggling a bit learning loadash and how to correctly pull the data I want with some more advanced tricks. Single objects and lookups are pretty simple but i'm trying to pull all array records by a groupId, if that groupId exists in another object that isn't the same.
For example:
Generic JSON example of objects, each are arrays of records.
Groups ..
{
groupId:
name:
code:
}
Options ..
{
groupId:
optionId:
name:
code:
}
The problem I'm having is pulling all Options only if that groupId exist in the Groups array in loadash.
I've tried some stuff like
var results = [];
_.forEach(Groups, function(g) {
var found _.find(Options, g, function(option, group) {
return option.groupId === group.groupId;
})
results.push(found);
});
I haven't had much luck figuring out the best way to filter these down.
Any words if wisdom would be appreciated, thanks!
Something like this should work,
var result = _.filter(Options, function(o) {
return _.filter(Groups, function(g) { return g.groupId == o.groupid; }).length > 0;
});
actually i think the inner search would perform better with find, since it returns the first match, not sure though
var result = _.filter(Options, function(o) {
return _.find(Groups, { 'groupId': o.groupid });
});
hope this helps.
I have the following objects:
var empAry= [{"empid":"101","name":"David"},{"empid":"102","name":"Sam"}..];//2000 records
var empAry2= [{"empid":"101","name":"David"},{"empid":"105","name":"Kevin"},{"empid":"109","name":"Robert"},{"empid":"110","name":"Rob"}..];//30000 records
I need to add new element to the empAry object and populate new element value based on the availability of that particular record in empAry2.
Expected Output:-
empAry= [{"empid":"101","name":"David", **"FounInempAry2":"Yes"**},{"empid":"102","name":"Sam", **"FounInempAry2":"No"}**..];//2000 records
If we can do it by jquery that would be good. Please help me.
It's hard to make sense of what FounInempAry2 is since the object structures are identical in both samples. I will assume that other properties exist and will use jQuery $.extend() to "merge" the properties.
First it is likely most efficient to loop through the big array once and create an object using the empid as keys.
var tmp = {};
$.each( empAry2, function(_, item){
tmp[ item.empid ] = item;
});
This creates an object like:
{
"101" : {"empid":"101","name":"David"},
"102" : {"empid":"102","name":"Sam"}
}
Now loop through first array and extend with whatever is in matching object in the tmp object
$.each( empAry, function(_, item){
$.extend( item, tmp[ item.empid ]);
});
Reference: $.extend() Docs
Try this:
var entry = {"empid":"<some id>","name":"<some name>"}
var filter = empAry2.filter(function(o){
return o.empid==entry.empid;
});
entry.FounInempAry2=(filter && filter.length>0)?"Yes":"No";
empAry2.push(entry);
Or
var entry = {"empid":"<some id>","name":"<some name>","FounInempAry2":"No"}
for(var i=0,length=empAry2.length;i<length;i++){
if(empAry2[i].empid==entry.empid){
entry.FounInempAry2="Yes";
break;
}
}
empAry2.push(entry);
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.