I am trying to join the values of an object/associative array to make changes to my code easier but I can't figure out how to properly join them. Here is my code:
$( document ).on( "click", ".taskstatus a", function ( event ) {
event.preventDefault();
classes = {
'OPEN': 'state_open',
'COMPLETED': 'state_completed',
'SKIPPED': 'state_skipped',
'REJECTED': 'state_rejected'
};
joinedClasses = classes.map(function(value, key){ return key; }).join(' ');
state = $(this).data('state');
taskID = $(this).closest('.task').attr('id').replace( 'task_', '' );
// Update checkbox icon
$(this).closest('.taskwrap').find('.taskcheckbox').data( 'icon', $(this).data('icon') );
// Update task class
alert( joinedClasses );
$(this).closest('.task').removeClass( joinedClasses ).addClass( classes[state] );
});
This code breaks at the map function since it doesn't see it as an array, whats the best way to accomplish joining the values of class so that they look like this: "state_open state_completed state_skipped state_rejected"?
You can use jQuery.map function. It is more forgiving and therefore allows usage on an associative array (like yours) as well as a traditional array:
joinedClasses = $.map(classes, function(e){
return e;
});
result:
["state_open", "state_completed", "state_skipped", "state_rejected"]
live example: http://jsfiddle.net/MK4f7/
this can then be joined using a space in the same way as your original:
joinedClasses = $.map(classes, function(e){
return e;
}).join(' ');
Since it's not an array you can use map. You need to use a for loop like below:
var classes = {
'OPEN': 'state_open',
'COMPLETED': 'state_completed',
'SKIPPED': 'state_skipped',
'REJECTED': 'state_rejected'
};
// Create a tmp array for the join
var joined = [];
// Loop over the object Literal.
// the var key is now the prop in the object.
for (var key in classes) {
var val = classes[key]; // gets the value by looking for the key in the object
joined.push(val);
}
// Join the array with a space.
joined = joined.join(' ');
Working fiddle
EDIT: accepted answer is better if you want to do it with jQuery, cheers.
If you can load linq.js, try this code:
joinedClasses = Enumerable.From(classes).Select("$.Value").ToArray().join(' ');
Related
I have an extension which loads a docking panel with a text field and a button. The functionality of this button would be to display the DB-ID of the item name given in the text field.
Something like:
Rubber = 2130
where Rubber is the input and 2130(db-id) will be the output
How can I achieve this?
Thanks in advance.
Would suggest using .search() method, which is a supported way:
viewer.search('Rubber', function(dbIds){
// here the dbIds is a list of dbIds, you can handle it
callback(dbIds); // handle the results async
}, function(error){
// handle errors here...
}, ['name'] /* this array indicates the filter: search only on 'Name'*/
)
And look here on how to improve performance on search.
There is no such API available currently, but a workaround can be used in this case. It's shown as the following:
//-- For the element type or element category like "Floor [" or "Floor"
var it = viewer.model.getData().instanceTree;
var strIdx = it.nodeAccess.strings.indexOf( "Floor [" );
// var strIdx = it.nodeAccess.strings.indexOf( "Floor" );
var nameIdx = it.nodeAccess.names.indexOf( strIdx );
for( var key in it.nodeAccess.dbIdToIndex ) {
if( it.nodeAccess.dbIdToIndex[key] === nameIdx ) console.log( key )
}
//-- For element name like "Floor[766598]":
var it = viewer.model.getData().instanceTree;
var eidIndex = it.nodeAccess.nameSuffixes.indexOf( 766598 );
for( let key in it.nodeAccess.dbIdToIndex ) {
if( it.nodeAccess.dbIdToIndex[key] === eidIndex ) console.log( key )
}
P.S. Since this is just a workaround, not the formal solution. You would have to use it at your own risk.
If you want to avoid using the search() method, you could also create your own Object that maps the name to ID's. This is a temporary workaround until Autodesk implements its own method.
var instanceTree = viewer.model.getData().instanceTree; // Get model tree
var allDbIds = Object.keys(instanceTree.nodeAccess.names); //get array of all ID's
var forgeNameMap = {} //Empty array for mapping names
allDbIds.map(function(id) {
forgeNameMap[instanceTree.getNodeName(id)] = id
})
let rubberID = forgeNameMap["Rubber"]
I'm trying to simply replace the invalid date with an empty string. I'm iterating through an array of objects, but whenever I try to use _.each() I get lost. If someone could show me a way to iterate through all the fieldsToCheck items in my list, that would be rad.
massage.removeBadDates = function(data){
var fieldsToCheck = [
"partsLeadTime",
"statusDate",
"targetDate",
"revisedTargetDate",
"quoteDate",
"dispositionDate",
"serviceDate",
"finalDate",
"receivedDate"]
var newData = []
_.map(data, function(value, index, list){
newData.push(value)
//single
if (list[index].partsLeadTime == "1900-01-01T00:00:00"){
newData[index].partsLeadTime = ""
}
});
return newData
};
You pretty much want something like this:
_.each(fieldsToCheck(function(field) {
if (list[index][field] == "1900-01-01T00:00:00") {
newData[index][field] = ""
}
});
I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined) and then putting these objects in an array (all working fine here).
When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value.
I am using:
arr.splice(index,1);
to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.
for e.g. [object,object,object]
[
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
]
after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];
or
if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.
Why is there null and how can I remove that from array. (don't want to iterate again to check null).
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});
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);
I have a post function that returns a 2d array. How would I go about displaying each of the elements in it? My code looks something like this :
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(result) {
//$("#CustomerList tbody").append($(result));
var myarray = new Array()
myarray = result;
alert(myarray);
});
what the alert returns is "System.String[][]". How can i go about appending each of the values from my array to my div tag called #divComparativeQuestions.
For example:
var data = new Array();
for(var i=0;i<myarray.length;i++){
data.push(myarray[i].join(', '));
}
$('#divComparativeQuestions').html(data.join('<br/>'));
(hope this works, not tested :), but you get the idea )
I'm guessing you want something like:
// given an array [[1,2],[3,4]] with a desired result of <div>1234</div>
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(data) {
if(data) {
var div = $('#divComparativeQuestions');
$.each(data, function(index, element) {
div.append(element); // will be inner array of [1,2] or [3,4]
});
}
});
All pretty basic stuff, in this case I'm taking advantage of the fact js typically flattens array as strings without commas to get the desired out put, but if you want to delimit them items somehow or wrap them in tags or whatever, it's easy enough to work out by taking a few seconds to browse http://docs.jquery.com