I have an object that I am iterating through using JQuery's each function. However, the solution posted in this stack overflow post doesn't work when I tried using the length property. I got undefined in the console when I tried getting a length property value, which I believe this is because I am iterating through an object and not an array.
My code:
$.each(attributes, function(key, value) {
attrKey = key;
attrVal = value;
console.log(attributes.length); //returns undefined
//do something if it is the last element
});
Try plain Javascript instead:
for (var key in attributes) {
var value = attributes[key];
// process key,value...
}
Edit:
If you're trying to get the last key/value in an object, you can't. Javascript objects are unordered, meaning that they do not keep track of when additional key/value assignments are made. If order is important, I would recommend changing attributes be an array of objects, where each object is a single key/value, or use a 3rd party library, like this - https://github.com/trentrichardson/Ordering.
If you'd like to get the number of keys in attributes, use Object.keys:
Object.keys(attributes).length
Try
var index = 1;
$.each(attributes, function(key, value) {
if(Object.keys(attributes).length == index)
{
// Do something
}
index++;
});
per #PaulFrench's comment:
length = Object.keys(attributes).length;
if(n < length) {
//do something
}
Related
I am just curious about this.
Let's say I have an array of objects and I create 1 object, lets name the array of objects items and the object item.
I want to get a particular item in my array of items by using the following code:
//gets an item base on ID
function get_item(td){
var item = undefined;
$.each(items, function(i, val) {
if(val.item_id == td){
item = val;
}
});
return item;
}
The get_item() basically gets an object matched with the supplied id.
So my question is this. What if I changed the properties of item will it also changed the properties of an object associated with it within the array?
Thank you very much!
What if I changed the properties of item will it also changed the properties of an object associated with it within the array?
Yes.
Objects are not copied. Instead, references to the objects are passed around. Simplest example:
var a = [];
var b = a;
b.push(1);
console.log(a); // logs [1]
Many object-oriented programming languages work like this.
The value of the object inside the array will also change because it's a reference. If you want more information I highly recommend reading Objects and Prototypes.
If you don't want it to change then you should use something like lodash's _.clone() function.
Also you could use filter to get the object:
function get_item(td){
return items.filter(function(item) {
return item.id === td;
})[0];
}
You can update you function to:
var data= array();
function get_item(propertyValue, propertyName){
var retval;
for(var i = 0; i < data.length; i++){
if(data[i][propertyName]==propertyValue){
retval = data[i];
break;
}
}
return retval;
}
Use it
var item1 = get_item(1,"id");
var item2 = get_item("john","name");
This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).
I'm working on a little something where figures are shown or hidden, based on what checkboxes on a list are checked or not.
To this end, I need to first collect an array of only the checkboxes that have been checked, so I can use their values for comparison with the list later on.
In order to do this, I wrote a little function, with the help of jQuery:
var findIndexesWithValue = function(arr, val) {
//Find the correct indexes and put them in an array, for later use.
var indexArray = [];
$.grep(arr, function(elementOfArray, indexInArray) {
//Get all indexes where the value corresponds
if (arr[indexInArray] === val) {
indexArray.push(indexInArray);
}
});
return indexArray;
};
For those not familiar with $.grep: http://api.jquery.com/jQuery.grep/
My question is: am i re-inventing the wheel here? I made this because indexOf() returns only the first index at which a value is encountered and not all of them.
$.grep isn't really best jQuery array method for this situation.
$.map will work more effectively
var indexArray = $.map(arr, function(elementOfArray, indexInArray) {
return elementOfArray == val ? indexInArray : null;
});
console.log( indexArray);
DEMO: http://jsfiddle.net/x8qgq/1/
I have the following and I am trying to figure out how to search the array of objects - the call() function is called multiple times ?
var arr = [];
var newData;
function call() {
newData = $('a').attr('href');
if($.inArray(newData, arr) == -1) {
$.post('/blah', function(data) {
arr.push(data);
});
}
}
data is like [object{ }] so arr becomes [[object{id='1', myUrl=''}], [object{id='2', myUrl='' }]].
What I am trying to figure is out whether newData is contained within the arr ?
If the array contains objects, $.inArray will not work. This is because objects are only equal if they are the same object, not just contain the same values.
$.inArray won't work here also because newData is a string. It's not gonna search inside each object for you, you need to that yourself, with your own loop.
Something like this:
newData = $('a').attr('href');
$.each(arr, function(){
if(this.myUrl === newData){
$.post('/blah', function(data) {
arr.push(data);
});
return false; // break once a match is found
}
});
The Array arr will contain a list of objects. Why would newData be "contained" within the arr? They are two separate variables.
Update - Upon further inspection this line is no good:
if($.inArray(newData, arr) == -1) {
You are essentially saying look for newData in the arr (which is empty).
Update - Here is some sample code that should work. Here I am treating data as a plain old object (not an array of objects) with a property named "url".
http://jsfiddle.net/nWh6N/
I have a Json like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"}}.
So ideally i should get length as 1 considering i have only 1 value on 0th location.
what if i have a JSON like this
{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}
I am getting the value as undefined if i do alert(response.length); where response is my JSON as mentioned above
Any suggestions?
Objects don't have a .length property...not in the way you're thinking (it's undefined), it's Arrays that have that, to get a length, you need to count the keys, for example:
var length = 0;
for(var k in obj) if(obj.hasOwnProperty(k)) length++;
Or, alternatively, use the keys collection available on most browsers:
var length = obj.keys.length;
MDN provides an implementation for browsers that don't already have .keys:
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
Or, option #3, actually make your JSON an array, since those keys don't seem to mean much, like this:
[{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}]
Then you can use .length like you want, and still access the members by index.
let _json = '{"0":{"parent_id":1649,"id":"1803","last_update_on":"2010-12-24 07:01:49","message":"dhb;lxd","created_by_id":"21","created_by_name":"Amol Deshpande"},"1":{"parent_id":1649,"id":"1804","last_update_on":"2010-12-24 07:02:49","message":"amol","created_by_id":"21","created_by_name":"Amol Deshpande"}}';
let your_json = $.parseJSON(_json);
const size = Object.keys(your_json).length;