I'm having trouble deleting/removing an item from an Array in jQuery. I've run the results in console.log() and it shows up as an Object. I've created a function which returns a json string and then I parses it, an example below:
var ret = jQuery.parseJSON($.return_json(data));
It works nicely, however, I am running an $.each loop which removes items from that array/object.
var old = $("element").find("li[rel=item]");
$.each(old, function(index, value) {
ret.splice($(value).attr("id"), 1);
});
Above, I am searching for elements with attribute rel = item. The same element contains an id which is related to the index of the function which returns the json parsed variable.
I ran Developers Tools in Google Chrome to see the error and it prints:
Uncaught TypeError: Object #<Object> has no method 'splice'
Any words of guidance will be much appreciated. Thanks.
It seems like ret is not actually an array (and likely an object (ex: {someName: "someVal"}) instead).
I'm also making an assumption that you mean for $(value).attr("id") to be a string identifier like someName in the object example above. If that is the case and you are working with an object and you do have the appropriate property identifier, then luckily there is an easier solve than splice.
Try:
$("element").find("li[rel=item]").each(function() {
delete ret[$(this).attr("id")];
});
splice is only a method of arrays, not objects. ret in this case, is an object, not an array.
If you are trying to remove specific elements from an object, you can do this:
$("element").find("li[rel=item]").each(function(i,v){
delete ret[v.id];
});
ps. You can use .each instead of $.each.
If you really want to make the object into an array, you can simply loop through it and push the elements into an array.
var obj = {"1":"item 1", "2": "item 2", "3": "Item 3"};
var arr = [];
for(i in obj){
if(obj.hasOwnProperty(i)){
arr.push(obj[i]);
}
}
ret is the JSON object containing the array, and you can't splice it. You need to reference whatever you called the array within the object and splice that.
(Would help if you posted the code where you define the array).
Related
I'm trying to build an array to create a menu system where each index has 2 objects, a name and a subarray of Strings.
I tried something like this:
var menus = [];
menus.push({title:"Aztec", mySubArray:{"String1", "String2","String3"} });
but that doesnt seem to be the right syntax. any ideas?
thanks
You have a syntax error, mySubArray has to be an array []
var menus = [];
menus.push({title:"Aztec", mySubArray:["String1", "String2","String3"] });
mySubArray is not a valid object, because it's missing property names, which makes it an array. You can fix this by either making mySubArray an array:
mySubArray:["String1", "String2","String3"]
or by adding property names to make it an actual object:
mySubArray:{1: "String1", 2: "String2",3: "String3"}
The issue isn't with the fact that it's a "sub array" being pushed, only with the syntax of the actual mySubArray value.
I'm trying to load text of all divs that have a particular class into an array, but this
var temp = $('.theClass').text();
temp = temp.toArray();
console.log(temp);
keeps giving me the error
Uncaught TypeError: Object has no method 'toArray'
And
var tempArr = [];
var temp = $('.theClass').text();
for (var t in temp){
tempArr.push(t);
}
console.log(tempArr);
results in an array filled with many, many objects within objects just filled with integers.
An explanation of how to do this properly can be found here, but I wonder if someone could provide me with an explanation for why I get these errors. Thanks!
You can use map to iterate over each element of the matched set and return some data (in this case, the text). You can then use get to convert the resulting jQuery object into an actual array:
var arr = $('.theClass').map(function () {
return $(this).text();
}).get();
Your first attempt fails because the text method returns a string, and strings don't have a toArray method (hence your "Object has no method" error).
Your second attempt fails because you're iterating over the string with the for...in loop. This loop iterates over the characters of the string. Each iteration t is assigned the index of the character, so you end up with an array, with one element for each character in the string. You should never really be using a for...in loop for iterating over anything other than object properties, and even then, you should always include a hasOwnProperty check.
I know this isn't the best way to do it, but I have no other choice :(
I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:
(for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
(Soruce : Loop through Json object).
However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.
As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?
A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:
var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)
alert(object[keysbyindex[i]]);
But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop
var counter = 0; // if you need it
for (var key in object) {
alert(object[key])
counter++;
}
? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.
Based on Bergis anserwer this is my solution:
var keysbyindex = Object.keys(this);
alert(this[keysbyindex[index]]);
return this[keysbyindex[index] || ""];
However, I think (not tested) it's extremly bad regaring performace and shouldn't be used! But desperate times require desperate measures.....
I don't think you can actually achieve this without creating your own parsing of JSON. You're writing that you want to go trough a JSON-object, but what you're actually trying to do is go trough a plain old Javascript object. Json is simply a string-representation used to transfer/store said object, and in here lies the main problem: the parser that transforms the string into an actual object (ie. the browser in most cases) can chose to ignore the order it finds the properties if it want to. Also, different browsers might have different approaches to parsing JSON for all you know. If they simply use a hash-map for the object that it's simple to loop through it, but the order won't be dependent on the order of the keys in the file, but rather the keys themselves.
For example, if you have the json {"b":"b","a":"a"} and do the for in loop, under some implementations you might end up with a comming first, and in others you might end up with b.
var jsn = {keyName: 'key value result come here...'};
var arr = jsn ? $.map(jsn, function (el) { return el }) : [0];
console.log(arr[0])
$('.result').text(arr[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="result"></span>
Can someone tell me how to update the following code to just get the first item that's returned in an object (data)? I know using each() for just one item isn't very efficient and would like to improve it.
$(data).each(function(num, entry){
if ( num > 1 ) return false;
});
Here's an example of what data is:
[
{
"id": 1,
"title": "My post",
"permalink":"http:\/\/site.com\/page.html\/",
"date":" 2011-05-10
}
]
Update 2:
As data is just an array (I assume the JSON is already parsed (if not you can use jQuery.parseJSON or JSON.parse)), you can get the first element with simple array access:
var first = data[0];
Read more about arrays.
Old answer:
Try
$(data).first() // returns jQuery object
// or
$(data).eq(0) // returns jQuery object
// or
$(data).get(0) // returns DOM object
// or
$(data)[0] // returns DOM object
depending on the data you have and what you want to do.
Update:
If data is actually a JavaScript object, then there is no need to pass it to jQuery (jQuery is mostly for working with the DOM).
Just loop over it with
for(var prop in data) {
}
But you cannot get the "first" property because they are unordered.
If it is an array, just use data[0].
To help you more, you should post what data is.
You can do this:
$(data).get(0); //same as $(data)[0]
I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.