I have a backbone collection in the below format, comma separated values in one of the attributes
var my_collection = {
{
"name" : "test1",
"field" : "a,b,c"
},
{
"name" : "test2",
"field" : "a,c"
},
};
I wanted to filter the attribute 'field' of value 'a' from the above collection, so that it should return test1 and test2.
I tried using var filtered = my_collection .where({field: 'a'}); this will do the exact match of "field:a" only.
Any solution to filter the test1 and test2 when the user given the value "field:a"
Thanks in advance.
Use _.filter -- it's like _.where, except lets you specify a function as the predicate. Then use split along with indexOf to check if "field" contains your item:
my_collection.filter(function(x) {
return x.field && x.field.split(',').indexOf("a") != -1;
})
Fiddle
Related
I have an array which contains many objects(all this data will come via ajax call, for example lets say there are only 3 records).
data : [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];
Is there any way to loop through entire array and find objects with same id and concatenate their names and filter the array to be like this
data : [{name : "a,c",id : "100"},{name : "b",id:"101"}]
Thanks
You can use forEach() loop and check if id exists and concat name to that value.
var data = [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];
var result = []
data.forEach(function(e) {
//Check if property with current object id exists in object provided as thisArg param and if it doesn't exists set its value to current object and push it to result array
if(!this[e.id]) this[e.id] = e, result.push(this[e.id])
// if it does exists then concat name of current object to name of existing one that had the same id
else this[e.id].name += ',' + e.name
}, Object.create(null))
console.log(result)
I suggest to use a hash table, which is used as a closure of the callback function. Then iterate over the objects and thest if the hash exists or not. If it exists, add the name to the name property of the object, otherwise create a new object with the actual data and push it to the result set.
Return the temporary array in Array#reduce.
var data = [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];
data = data.reduce(function (hash) {
return function (r, a) {
if (hash[a.id]) {
hash[a.id].name += ',' + a.name;
} else {
hash[a.id] = { name: a.name, id: a.id };
r.push(hash[a.id]);
}
return r;
};
}(Object.create(null)), []);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I'm trying to filter some JSON data to search for job roles that starts with a certain string.
The JSON looks like :
"periods": [
{
"periodName": "Week1",
"teamName": "Tango",
"roleName": "SoftwareEngineerII",
"roleExperience": "2",
"id": "cc1f6e14-40f6-4a79-8c66-5f3e773e0929"
},
...
]
I want to filter for roleName that starts with "Software" so that I can see a list of all Software Engineer levels, and it filters out other roles.
I'm not sure how to do a "starts with" or "contains" here.
You are trying to filter the array where one of the string properties contains a value... How else would you check if a string contains another string?
You could use a regex:
var str = 'SoftwareEngineerII';
if (str.match(/^software/i)) {
// it starts with 'software'
}
So you need to convert this to a predicate that could be used in your filter.
var query = Enumerable.From(data.periods)
.Where("!!$.roleName.match(/^software/i)")
.ToArray();
may I know how to push var obj= [{}] in .each? for example like this.
$.each(maintasks_row, function(index, maintasks_val) {
obj.push([{
"name" : maintasks_val.task_name,
"desc" : "",
"values" : [{
"from" : "/Date("+maintasks_val.time_start+")/",
"to" : "/Date("+maintasks_val.time_end+")/",
"label": maintasks_val.task_name,
"customClass" : "ganttRed"
}]
}]);
});
I'm using this for $(".gantt").gantt({source: obj});
On this site the var data is [{}] is this an object? and how can I insert it?
thank you
.push does not require you delcare it as an array ( like you tried obj.push([{ - unless of course you are pushing an array into an array
Just simply ...
obj.push({"name" : maintasks_val.task_name, ..
adds a new single item intto the array
Update as comment , yes, declare obj as a typeof array first
var obj=[];
This is now the same as the data array you have shown in your docs example - and we can now .push() into it.
I have a string containing a list of dictionary.
I want to compare by checking their keys not value. is there any way to do that.
data = '[{ "group1" : "T1"}, { "group1" : "T2"}, { "group2" : "T3"}]';
how can i compare these dictionaries on the basis of their keys. for example, i have used:
dataObj = eval(data); //generate 3 objects for data.
here dataObj[0] will refer to object of { "group1" : "T1"}
to do it i have done following code:
for(i=0;i<dataObj.length;i++){
if (dataObj[i].key == dataObj[i].key){ //<-- i am not getting what to do to compare their keys i.e. "group1" and "group1"
//my other statements
}
}
Do not use eval but JSON.parse](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse) instead. If it's not available in some old browsers there are plenty of implementation that are less vulnerable to attack than just eval.
Saying that, having:
var data = '[{ "group1" : "T1"}, { "group1" : "T2"}, { "group2" : "T3"}]';
var array = JSON.parse(data);
Will generate an Array of Object, each of them has one own property called group1 or group2. To be clear:
var myobj = {"group1" : "T1"}
Is an Object literal, and it's exactly the same of:
var myobj = new Object();
myobj.group1 = "T1";
So, as you can see, there is no key property anywhere.
It's not clear what you want to compare, also because the third object seems have a different property's name.
Updated:
About your comment, the point here is that there is no "object key" but just object's properties. It means, you need to know the name of the "key" in advance in order to use it:
array[0].group1 === array[1].group1 // false, one is "T1", one is "T2"
If you want to have a key properties that contains the value "group1", than your objects needs to be different:
var data = '[{"key" : "group1", "value": "T1"}, {"key": "group1", "value" : "T2"}, { "key" : "group2", "value" : "T3"}]'
Then, you can have:
var array = JSON.parse(data);
array[0].key === array[1].key // true, both are "group1"
array[0].value === array[1].value // false, one is "T1", one is "T2"
I have combed the web to try and give myself some understanding as to what the following means as it pertains to the object below. What does "a" and "b" mean? Why is it significant?
students.sort(function(a, b){
return a.fn-b.ln
})
var students = [{
fn : "Stone",
ln : "Carpenter",
scores : [61,99,73,68,80,62,176,78]
},
{
fn : "Samson",
ln : "Sears",
scores : [68,193,91,190,95,65,171,75]
},
{
fn : "Quin",
ln : "Morton",
scores : [79,95,161,92,182,163,198,182]
},
{
fn : "Qunitessa",
ln : "Hardy",
scores : [99,65,75,69,77,67,86,78]
},
{
fn : "Ashley",
ln : "England",
scores : [147,70,81,64,148,71,70,63]
},
{
fn : "Thaddeus",
ln : "Hutchinson",
scores : [99,190,188,185,160,88,89,76]
},
{
fn : "Yeo",
ln : "Hayes",
scores : [88,64,199,165,198,76,74,81]
},
{
fn : "Rylee",
ln : "Larson",
scores : [71,126,63,71,168,173,175,88]
}
];
I understand that the anonymous function will return a value of -1,0,1, but what is the significance of the arguments a and b since I will not be passing any values (such as employees.sort(a.something, b.something)) when I call the function. With the above data I need to sort by clicking on one of the headers of my table -- which will involve sorting string and number values. Any ideas as to how to sort the nested values in the "scores" array? How would I go about sorting via the first/last name?
The sort method of an Array will take your sorting function and apply it when necessary to compare two elements and determining their sort order. a and b will be two elements of the Array you are sorting.
To sort your objects alphabetically by last name, you will need a sorting function like this one:
function lastNameCompare(a, b) {
var sortFieldA = a.ln.toLowerCase();
var sortFieldB = b.ln.toLowerCase();
return sortFieldA == sortFieldB ? 0 : (sortFieldA < sortFieldB ? -1 : 1);
}
Remove the .toLowerCase() if you want your sort to be case sensitive. To sort for something like "last name, first name" you would use the following lines instead:
var sortFieldA = (a.ln + ", " + a.fn).toLowerCase();
var sortFieldB = (b.ln + ", " + b.fn).toLowerCase();
To also sort the scores in your data you will need to perform a sort on every entry of your data set:
for (var i = 0; i < students.length; i++) {
var student = students[i];
student.scores.sort();
}
Note that you don't need an explicit sorting function in this case, since sort will use numeric sort order by default.
.sort takes a callback. It will then pick two elements from the array and pass them to the callback function. The callback function returns which element is greater. .sort rearranges the two elements in the array based on that information. It then takes two other elements and passes them into the callback. Rinse, repeat until the array is sorted.
a and b are simply the variables for "an element" and "another element". Call them whatever you like. There's no significance to the naming.