Make object Object as index of array (Javascript) - javascript

I've been using a crossword app from this repo: https://github.com/jweisbeck/Crossword . The problem is that the program uses jquery version 1.6.2 and my whole project uses jquery-3.1.1 version. Particularly, the error arises here:
buildEntries: function() {
var puzzCells = $('#puzzle td'),
light,
$groupedLights,
hasOffset = false,
positionOffset = entryCount - puzz.data[puzz.data.length-1].position; // diff. between total ENTRIES and highest POSITIONS
for (var x=1, p = entryCount; x <= p; ++x) {
var letters = puzz.data[x-1].answer.split('');
for (var i=0; i < entries[x-1].length; ++i) {
light = $(puzzCells +'[data-coords="' + entries[x-1][i] + '"]');
if($(light).empty()){
console.log($(light));
$(light)
.addClass('entry-' + (x-1) + ' position-' + (x-1) )
.append('<input maxlength="1" val="" type="text" tabindex="-1" />');
}
}
}
// Put entry number in first 'light' of each entry, skipping it if already present
console.log(entries);
console.log(puzz.data);
for (var i = 0; i < entryCount; i++) {
$groupedLights = $('.entry-' + i); 
if(!$('.entry-' + i +':eq(0) span').length){
$groupedLights.eq(0)
.append('<span>' + puzz.data[i].position + '</span>');
}
}
util.highlightEntry();
util.highlightClue();
$('.active').eq(0).focus();
$('.active').eq(0).select();
}
The error arises at line with
light = $(puzzCells +'[data-coords="' + entries[x-1][i] + '"]');
The browser shows this error:
Error: Syntax error, unrecognized expression [object Object][data-coords="1,6"]
I believe this is related to the jQuery version. Or maybe the program uses [object Object] as index. Not sure as I am new in jQuery. I tried to use jQuery Migrate, but it didn't help. Also, I tried to use that jQuery 1.6.2, but a web browser could not find jQuery at all as I am using Typescript and had to install jQuery through .d.ts file. Any tips or advises? Thanks in advance

As the title says:
Make object Object as index of array
That is not possible with standard Objects/Arrays, but you can use a Map for that:
let map = new Map(),
key = {id: '##'};
map.set(key, [1,2,3,4,5]);
console.log(map.get(key)); //[1,2,3,4,5]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

The [object Object] in the string shown in the error is because a jQuery object is being appended to a string to create a selector, which is invalid.
In your code, it's this line causing the problem:
var puzzCells = $('#puzzle td') // holds jQuery object
// later on...
light = $(puzzCells + '[data-coords="' + entries[x-1][i] + '"]');
This is nothing to do with the version of jQuery being used as it's a syntax issue.
To fix this you should use filter() on the puzzCells object, instead of appending it to a selector. Try this:
light = puzzCells.filter('[data-coords="' + entries[x-1][i] + '"]');

You are concatenating an object (puzzCells) and a string. When JavaScript detects an string concatenation tries to convert all the variables to strings before concatenating them. In plain JavaScript, if you do WHATEVEROBJECT.toString() you will receive [object Object], that's why you see an error containing that message.
This is not jQuery version problem, as this happens at the very low level (JavaScript).
puzzCells is a jQuery object, where you can call jQuery methods. In this case you need the filter method, like this:
light = puzzCells.filter('[data-coords="' + entries[x-1][i] + '"]');
Check out more info right here: http://api.jquery.com/filter/

Related

JS IOS issue: null is not an object

I have two arrays:
var tableIdsSold = [3, 38, 43, 44];
var tableIdsBook = [40];
I receive array elements from backend, right after "body" tag opens.
Then, before "body" tags closes, i put link to "main.js".
In "main.js" i have this code runnin:
for (var i = 0; i < tableIdsSold.length; i++) {
document.querySelector('[data-circleId="' + tableIdsSold[i] + '"]').classList.add('purchased');
}
and same for second array.
So i just run through array, use array element as id. When script finds element with right id - it should add class to html tag "circle".
So the problem is: script works everywhere, but not in IOS. If i open this page in mac (safari/chrome) or iphone 5/6 (safari/chrome), i get this error in console:
TypeError: null is not an object (evaluating 'document.querySelector('[data-circleId="' + tableIdsSold[i] + '"]').classList')
Script runs in "window.onload" function. What's causing the problem?
Sorry for bad english
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
You need to check if this document.querySelector('[data-circleId="' + tableIdsSold[i] + '"]') null then no need to do action.
CODE SNIPPET
for (var i = 0; i < tableIdsSold.length; i++) {
let circleId = document.querySelector('[data-circleId="' + tableIdsSold[i] + '"]');
if (circleId) {
circleId.classList.add('purchased');
}
}
So the problem was: somehow ios html interpretator writes "data-circleId" class as "data-circleid". My JS script couldn't find "data-circleId" because of this.

How to iterate through array of objects using javascript

I have an object whose members are objects and arrays. This is what it looks like in the console:
Object {UserAccount: Object}
UserAccount: Object
UserAccountId: 2
User: Object
UserId: 2
UserRoles: Array [2]
0: Object
UserRoleId: 2
RoleId: 1
Org: Object
OrgId: 2
OrgName: "Little League"
1: Object
UserRoleId: 7
RoleId: 1
Org: Object
OrgId: 5
OrgName: "Youth Soccer"
I need a loop that will insert a child element for each OrgName. Here is the HTML so far:
<div class="sp">
<div class="tabs">
<!-- Want to insert element here -->
</div>
I am trying to write a javascript loop and it isn't working. I think the reason is that I don't know how to refer to members of objects inside other objects. This is from the .js file:
var i;
for (i in userAccount.User.UserRoles) {
$('.tabs').append('<span>' + Org.OrgName + '</span>');
}
When I run it I get this error:
Uncaught TypeError: Cannot read property 'UserRoles' of undefined
Please help!
Since you're looping through an array, use the iterative for loop.
var roles = UserAccount.User.UserRoles;
for(var i = 0; i < roles.length;i++){
var role = roles[i];
$('.tabs').append('<span>' + role.Org.OrgName + '</span>');
}
try
UserAccount.User.UserRoles.forEach(function(userRole) {
$('.tabs').append('<span>' + userRole.Org.OrgName + '</span>');
});
You can do a regular for loop as well. Or you can implement your own one as a utility function, as using a regular one is frustrating, so you DRY instead of repeating yourself :
var each = function(elements,fn) {
for (var i = 0; i < elements.length && !fn(elements[i], i++););
};
Looks good so far. But it looks like a mixture of forEach and for loops.
This is untested but adding userAccount.User.UserRoles[i] before Org.OrgName should work.
var i;
for (i in userAccount.User.UserRoles) {
$('.tabs').append('<span>' + userAccount.User.UserRoles[i].Org.OrgName + '</span>');
}
Another option. One that I find easier to read, is using a forEach loop.
userAccount.User.UserRoles.forEach(function (role) {
$('.tabs').append('<span>' + role.Org.OrgName + '</span>');
});
Note: forEach is unssupported in IE8. If this is a supported browser for your application, try using jQuery or Underscore which provide an IE8 friendly forEach option. Both of which are called each $.each() _.each()
There is this element.querySelector() for this job. You just do like
var myParentElement = document.querySelector(".sp"),
myElementToAppend = myParentElement.querySelector(".tabs");
myElementToAppend.appendChild(yourNewElement);

Find Value in Multidimensional Object Javascript

I'm trying to dynamically find a particular value inside a multi dimensional object.
To create the object, I'm doing this:
var inViewElements = {};
$('.story-section')
.each(
function(index){
var sectionId = 'story-section-' + Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
$(this).attr('id', sectionId);
var inViewHeight = $(this).height(),
inViewPosTop = $('#' + sectionId).offset().top,
inViewPosBottom = ((inViewPosTop + inViewHeight) - (inViewTolerence + inViewHeight));
inViewElements[inViewPosTop] = {
id: sectionId,
height: inViewHeight,
bottom: inViewPosBottom
};
debug('Inview', 'Object', sectionId);
debug('Inview', 'Height', inViewHeight);
debug('Inview', 'Offset Top', inViewPosTop);
debug('Inview', 'Offset Bottom', inViewPosBottom);
}
);
console.log(inViewElements);
And the output looks like:
What I'm trying to do is compare if another variable value, for example:
var currentPos = '3038';
Matches any of the objects keys. E.g. the 3038 or 2038 etc.
I'm struggling to figure this one out!
So you're trying to search for an object that contains a certain value?
There is no way to query an array/object in Javascript. As you're not using incremental indexes, I would suggest using a foreach loop, using a conditional statement to check whether the property you're trying to match is equal to the value you're looking for.
It would be quicker to use a for loop, however that would require incremental indexes.
If you r logging response variable through which ur output came then u can use this function
for(var x in response){
if( x == 3038) {
// do something
}
}
or
for(var x in response){
if(x == currentPos){
//dosomething
}
}
can u give me the proper code of how u put values to console log so i will edit the answer properly accourding to your question

How to add custom property in Titanium PickerRow?

Is this possible to add custom property in Titanium.UI.PickerRow?
In code below, I want to add custom property "index" (using applyProperties PickerRow method)
var daysRows = [];
for (var i = 0, j = days.length; i < j; i++) {
var currentRow = Ti.UI.createPickerRow({
title : days[i],
});
//adding custom property to identify selection
currentRow.applyProperties({index:i});
daysRows.push(currentRow);
};
But when iterating through that PickerRow object later, I could not get custom property index. What I am seeing is only Titanium properties title.
I am using code below to iterate available properties.
button.addEventListener('click', function(e) {
..............
var selectedRow = picker.getSelectedRow(2);
for (var k in selectedRow) {
Ti.API.info('key is: ' + k + ', value is: ' + selectedRow[k]);
}
});
What am I doing wrong? Is there any way I can add custom property in PickerRow?
This is old, but I am having similar issues. What I found as a workaround was to pass in the properties on creation rather than applying
Ti.UI.createPickerRow({title: 'My Row', customId: 1});
This may not suit everybody, but worked for me
This is Titanium/Appcelerator issue in Android platform.
This issue seen in Titanium SDK 3.1.1 and not fixed in 3.1.2 August 2013 release.
Update
jira.appcelerator.org/browse/TIMOB-14285 is now closed. This operation should work Release 6.1.0 onwards.

Reading a Javascript Object

How do I read a Javascript Object when I don't know what's in it?
I've been working on node.js and have a variable for which I really don't know what's in it. When I try sys.puts:
sys.puts(headers) // returns [object Object]
If there was something like a print_r in javascript, that would have been fine.
You can loop over its properties with
for (var item in headers)
{
// item is the name of the property
// headers[item] is the value
}
example at http://www.jsfiddle.net/gaby/CVJry/3/ (requires console)
If you want to limit the results to direct properties (not inherited through the prototype chain) then use as well the hasOwnProperty method.
example at http://www.jsfiddle.net/gaby/CVJry/2/
Most web browsers can use the JSON-object to print the contents of an object,
writeln(JSON.stringify(your_object));
If that fails, you can create your own stringifier;
var stringify = function(current) {
if (typeof current != 'object')
return current;
var contents = '{';
for (property in current) {
contents += property + ": " + stringify(current[property]) + ", ";
}
return contents.substring(0, contents.length - 2) + "}";
}
var my_object = {my_string: 'One', another_object: {extra: 'Two'}};
writeln(stringify(my_object));
You can loop through your object to know its properties & their values
Suppose your object is
var emp = {
name:'abc',
age:12,
designation:'A'
}
Now you can read its details in JS
for(property in emp ){
alert(emp[property] + " " +property);
}
If you have firebug in added in your Firefox browser, open it & write either in JS or JS window in Firebug console.
console.log(a);
If you need it just to check what's in an object (ie, it's relevant to you for some reason, but you don't need that functionality in your script), you can just use Firebug to get the object and check exactly what's in it.

Categories

Resources