This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I'm new to javascript. Someone please show me how to store a map in local storage. Below is what I've tried. After storing I don't seem to be able to iterate the map keys.
UDATE2: IT MIGHT BE THE serializeObject function.
Why am I using this function? Otherwise when I post in AJAX, I get:
Uncaught TypeError: Converting circular structure to JSON
UPDATE: LOOKS LIKE THE PROBLEM IS BEFORE IT EVER GOES INTO LOCAL STORAGE.
var reportId = getGUID();
var theReports = localStorage.getItem('reports');
if (theReports == null) {
theReports = {};
}
theReports[reportId] = JSON.stringify($('#reportInfo').serializeObject());
// HERE ALSO I AM SEEING HUNDREDS OF FIELDS. I EXPECTED JUST reportID. I AM NOT SEEING THE KEY reportId. THIS IS BEFORE IT GOES INTO LOCAL STORAGE.
for (var prop in theReports)
{
console.log(prop);
}
localStorage.setItem('reports', JSON.stringify(theReports));
var tReports = localStorage.getItem('reports');
// This prints out 1,2,3,...500 for every field in #reportInfo form
// What I was expecting is reportId1, reportId2 etc. and definitely not the id of each field of the report itself!
for (var property in tReports) {
if (tReports.hasOwnProperty(property)) {
console.log(property);
}
}
Here is the serializeObject function. Perhaps this is the problem.
$(function() {
$.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(){
// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
return json;
};
The for..in loop gives you only the keys and not the items itself. You get the items with tReports[property]
var obj = {
"1": "one",
"2": "two",
"3": "three"
};
for (var key in obj) {
console.log(key); //1, 2, 3
console.log(obj[key]); //one, two, three
}
var tReports = localStorage.getItem('reports');
The variable tReports now holds the stringified version of the reports object.
The localStorage and sessionStorage only store a key/value pair as a string.
So if you wan't to store an object you need to serialize it to a string.
localStorage.setItem('key', JSON.stringify(myObject));
If you wan't to retrieve it from storage you need to deserialize it first before you can use it.
var myObject = JSON.parse(localStorage.getItem('key'));
https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage?redirectlocale=en-US&redirectslug=DOM%2FStorage
Instead of:
console.log(property);
Do:
console.log(tReports[property]);
Since the property variable is the actual property name, not its value.
Related
I have the following json:
{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}
Currently I am trying to get its key-value with the below code:
var data = JSON.stringify(row);
var result = $.parseJSON(data);
$.each(result, function (k, v) {
//display the key and value pair
console.log(k, v);
});
The above code works fine and I can get my key-value from it.
Now what I am trying to get is the next key-value pairs within the $.each loop.
For example if in the loop the current key is "0" I want to get the next key "1" in the same call itself. If in the loop the current key is "1" I want to get the next key "$$hashKey" along with their values.
Is it possible to do so? I am open to code changes above if required.
You can use Object.keys to get the keys to an array, then run through it with a forEach to have access to the keys index. Important to note that objects are unordered, so your key order one time may differ from the next time:
var keys = Object.keys(obj);
keys.forEach(function(key, index) {
var nextIndex = index + 1;
if (nextIndex === keys.length) return; //out of bounds
var nextKey = keys[nextIndex];
});
Edit: As pointed out by the comments - if you want the keys in the same order each time, call .sort() on your keys array with your desired sort logic.
Understanding now that the goal is to retrieve keys in the order they appear in JSON, a couple of thoughts:
(1) if you control the source of the object ("row" in the OP code), don't represent it as an object. instead use an array of key-value pairs: [[0, "2"], [1, "2"], [$$hashKey, "object:35"], [undefined, "1"]].
otherwise, (2) roll your own JSON parser that returns an array of key-value pairs for an object. This post looks to be a sensible start. Or, you can vastly simplify the task if you are able to make certain assumptions about the values, for example, say you know that all values are strings...
// parse a string representing an object, returning an array of key-value pairs.
// assumes values are strings that do not contain commas or colons
function myProbablyNegligentlySimpleJSONParse(string) {
let trimmed = string.trim().slice(1, -1);
let components = trimmed.split(',');
return components.map(kvString => {
let kv = kvString.split(':');
return [ kv[0].trim(), kv[1].trim() ];
});
}
forEach passes the current index to the iterator function, so that int can be used to look ahead or behind in the iteration.
var data = '{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}';
let result = myProbablyNegligentlySimpleJSONParse(data);
result.forEach(function (pair, index) {
let [k, v] = pair; // now k and v are your key and value
console.log(`key is ${k} value is ${v}`)
if (index < result.length-1) {
let [nextK, nextV] = result[index+1];
console.log(`next key is ${nextK} next value is ${nextV}`);
}
});
You could turn your object into an iterable and which will return the next [key, value] pair each time you call next on the iterator:
function makeIterable(o) {
o[Symbol.iterator] = () => {
var keys = Object.keys(o);
var i = 0;
return {
next() {
var done = false;
var value = [keys[i + 1], o[keys[i + 1]]];
if (i >= (keys.length - 1)) {
done = true;
}
i++;
return {
value,
done
}
}
};
}
}
var jsonStr = '{ "0": "2", "1": "2", "$$hashKey": "object:35", "undefined": "1" }';
var obj = JSON.parse(jsonStr);
makeIterable(obj);
var itr = obj[Symbol.iterator]();
while (true) {
var item = itr.next();
if (item.done) {
break;
}
console.log(item.value);
}
I have a json, it is
{
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
}
I want to recovery the structure, like
{
"prop1": {
"sub1": {
"sub2" : "content1",
"sub3" : "content2"
}
},
"prop2": {
"sub1": {
"sub2" : "content3"
}
},
"prop3": {
"sub1": {
"sub2" : "content4"
}
}
}
I split the key with dot to get each key.
for (var key in json) {
var keySplit = key.split('.');
// Todo: recovery the structure
}
But not found a good solution.
Is anyone has solution?
You can use Array#reduce method.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
};
// iterate over the property names
Object.keys(obj).forEach(function(k) {
// slip the property value based on `.`
var prop = k.split('.');
// get the last value fom array
var last = prop.pop();
// iterate over the remaining array value
// and define the object if not already defined
prop.reduce(function(o, key) {
// define the object if not defined and return
return o[key] = o[key] || {};
// set initial value as object
// and set the property value
}, obj)[last] = obj[k];
// delete the original property from object
delete obj[k];
});
console.log(obj);
Answer by Pranav C Balan is right for the question you asked. But JSON's might not be as simple as you have mentioned above and can have array's also and few keys might not have "." in them. To handle all these cases you can use the following one.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.0.sub2": "content4"
};
function createJSONStructure(obj) {
Object.keys(obj).forEach(function(k) {
var prop = k.split('.'); //split on . to get elements
if(prop.length >1){ //If there is no dot just key the value as is.
let data = obj;//Copy the default object to data in each loop
for(i=0;i<prop.length-1;i++){
if(data[prop[i]]){ // Check if the key exists
if((prop[i+1].match(/^\d+$/) && !Array.isArray(data[prop[i]])) // Check if the next key is a digit and the object we have is a JSON
|| (!prop[i+1].match(/^\d+$/) && Array.isArray(data[prop[i]]))){ // Check if the next key is not a digit and the object we have is a Array
throw new Error("Invalid header data"); //If any of the above cases satisfy we cannot add the key so we can throw an error.
}
data = data[prop[i]]; // If key exisits make the data variable as the value of the key
}else {
if(prop[i+1].match(/^\d+$/)){ //If the key is not available see if the next parameter is a digit or string to decide if its array or string
data[prop[i]] = [];
}else{
data[prop[i]] = {};
}
data = data[prop[i]]; //Assign this new object to data
}
};
data[prop[i]] = obj[k]; //Finally add the value to final key
delete obj[k]; // delete the exisiting key value
}
});
return obj;
}
console.log(createJSONStructure(obj));
With an array of objects in a form like this:
[
{
1429={
{
8766={...},
8483={...},
7345={...}
}
}
},
{
9041={...}
}
]
how could i get back an array like this?:
[1429, 9041]
If the array of objects would be in another structure this code would work:
var obj = {
"5": "some",
"8": "thing"
};
var keys = $.map(obj, function (value, key) {
return key;
});
console.log(keys);
That would return [5, 8]. But in my example it just would return the indexes [0,1]
Even if I wouldn't know the depth of the object - is it possible to get the values on that level? I dont need the indexes, I need those values. I couldn't find anything about it so far. Any tips for me maybe?
P.S.: I know that i could work out something with these keys and a loop, but I'm just asking for a simplier way to do it.
Regards
you are looking for the keys in a json object, you can get them this way:
Object.keys(obj);
for the object example:
var obj = {
"5": "some",
"8": "thing"
};
you will get:
["5","8"]
for an array of object of this type:
var arrayObject = [{},{},{}];
you can use a map and get the keys:
var keys = arrayObject.map(function(k){
return Object.keys(k);
});
keys is an array of arrays of keys. Example, for the following object (similar to your data structure):
var l= [
{
1429:{
8766: "test",
8483:"test",
7345: "test"
}
},
{
9041: "test"
}
];
you will get:
[["1429"],["9041"]]
apply concat and you will get what you are looking for. Here how to apply concat in the case of multiple arrays.
var arrayOfKeys = [].concat.apply([], keys);
now you will get:
["1429","9041"];
In your specific case you could use
var keys = [];
root.forEach(function(v) { keys = keys.concat(Object.keys(v)); });
If instead you have a tree of arrays and you want the keys of all other objects instead (but not recursing into objects) then a simple recursive function would do it:
function topKeys(x) {
if (x && x.constructor === Array) {
var result = [];
x.forEach(function(item) {
result = result.concat(topKeys(item));
});
return result;
} else if (typeof x === "object") {
return Object.keys(x);
} else {
return [];
}
}
Consider:
var object = {
foo: {},
bar: {},
baz: {}
}
How would I do this:
var first = object[0];
console.log(first);
Obviously, that doesn’t work because the first index is named foo,
not 0.
console.log(object['foo']);
works, but I don’t know it’s named foo. It could be named anything. I just want the first.
Just for fun this works in JS 1.8.5
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
This matches the same order that you would see doing
for (o in obj) { ... }
If you want something concise try:
for (first in obj) break;
alert(first);
wrapped as a function:
function first(obj) {
for (var a in obj) return a;
}
they're not really ordered, but you can do:
var first;
for (var i in obj) {
if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
first = obj[i];
break;
}
}
the .hasOwnProperty() is important to ignore prototyped objects.
This will not give you the first one as javascript objects are unordered, however this is fine in some cases.
myObject[Object.keys(myObject)[0]]
If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
[
{"name":"foo", ...},
{"name":"bar", ...},
{"name":"baz", ...}
]
or maybe:
[
["foo", {}],
["bar", {}],
["baz", {}]
]
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.
for first key of object you can use
console.log(Object.keys(object)[0]);//print key's name
for value
console.log(object[Object.keys(object)[0]]);//print key's value
There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:
var keys = ["foo", "bar", "baz"];
Then use that to get the proper value:
object[keys[0]]
ES6
const [first] = Object.keys(obj)
Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:
_.pairs(obj)[0]
Then the key would be available with a further [0] subscript, the value with [1]
I had the same problem yesterday. I solved it like this:
var obj = {
foo:{},
bar:{},
baz:{}
},
first = null,
key = null;
for (var key in obj) {
first = obj[key];
if(typeof(first) !== 'function') {
break;
}
}
// first is the first enumerated property, and key it's corresponding key.
Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.
You could do something like this:
var object = {
foo:{a:'first'},
bar:{},
baz:{}
}
function getAttributeByIndex(obj, index){
var i = 0;
for (var attr in obj){
if (index === i){
return obj[attr];
}
i++;
}
return null;
}
var first = getAttributeByIndex(object, 0); // returns the value of the
// first (0 index) attribute
// of the object ( {a:'first'} )
To get the first key of your object
const myObject = {
'foo1': { name: 'myNam1' },
'foo2': { name: 'myNam2' }
}
const result = Object.keys(myObject)[0];
// result will return 'foo1'
Based on CMS answer. I don't get the value directly, instead I take the key at its index and use this to get the value:
Object.keyAt = function(obj, index) {
var i = 0;
for (var key in obj) {
if ((index || 0) === i++) return key;
}
};
var obj = {
foo: '1st',
bar: '2nd',
baz: '3rd'
};
var key = Object.keyAt(obj, 1);
var val = obj[key];
console.log(key); // => 'bar'
console.log(val); // => '2nd'
My solution:
Object.prototype.__index = function(index)
{
var i = -1;
for (var key in this)
{
if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
++i;
if (i >= index)
return this[key];
}
return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));
Suppose I have this code:
var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
Now if I wanted to remove "lastname"?....is there some equivalent of
myArray["lastname"].remove()?
(I need the element gone because the number of elements is important and I want to keep things clean.)
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the delete operator:
const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
Note that when delete is applied to an index property of an Array, you will create a sparsely populated array (ie. an array with a missing index).
When working with instances of Array, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice or Array#pop.
Note that the delete operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o, then o will subsequently be garbage collected in the normal way.
Using the delete operator can affect JavaScript engines' ability to optimise code.
All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:
alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);
And, as already indicated, you "remove" a property from an object via the delete keyword, which you can use in two ways:
delete myObj["SomeProperty"];
delete myObj.SomeProperty;
Hope the extra info helps...
None of the previous answers address the fact that JavaScript does not have associative arrays to begin with - there is no array type as such, see typeof.
What JavaScript has, are object instances with dynamic properties. When properties are confused with elements of an Array object instance then Bad Things™ are bound to happen:
Problem
var elements = new Array()
elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]
console.log("number of elements: ", elements.length) // Returns 2
delete elements[1]
console.log("number of elements: ", elements.length) // Returns 2 (?!)
for (var i = 0; i < elements.length; i++)
{
// Uh-oh... throws a TypeError when i == 1
elements[i].onmouseover = function () { window.alert("Over It.")}
console.log("success at index: ", i)
}
Solution
To have a universal removal function that does not blow up on you, use:
Object.prototype.removeItem = function (key) {
if (!this.hasOwnProperty(key))
return
if (isNaN(parseInt(key)) || !(this instanceof Array))
delete this[key]
else
this.splice(key, 1)
};
//
// Code sample.
//
var elements = new Array()
elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]
console.log(elements.length) // Returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop")) // Returns false as it should
console.log(elements.length) // returns 1 as it should
That only deletes the object, but it still keeps the array length the same.
To remove the element from the array, you need to do something like:
array.splice(index, 1);
While the accepted answer is correct, it is missing the explanation why it works.
First of all, your code should reflect the fact that this is not an array:
var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;
Note that all objects (including Arrays) can be used this way. However, do not expect for standard JavaScript array functions (pop, push, etc.) to work on objects!
As said in accepted answer, you can then use delete to remove the entries from objects:
delete myObject["lastname"]
You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.
There is an elegant way in the Airbnb Style Guide to do this (ECMAScript 7):
const myObject = {
a: 1,
b: 2,
c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }
Copyright: https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90
As other answers have noted, you are not using a JavaScript array, but a JavaScript object, which works almost like an associative array in other languages except that all keys are converted to strings. The new Map stores keys as their original type.
If you had an array and not an object, you could use the array's .filter function, to return a new array without the item you want removed:
var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
return item !== 'Smith';
});
If you have an older browser and jQuery, jQuery has a $.grep method that works similarly:
myArray = $.grep(myArray, function(item) {
return item !== 'Smith';
});
Use method splice to completely remove an item from an object array:
Object.prototype.removeItem = function (key, value) {
if (value == undefined)
return;
for (var i in this) {
if (this[i][key] == value) {
this.splice(i, 1);
}
}
};
var collection = [
{ id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
{ id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
{ id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];
collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");
You are using Object, and you don't have an associative array to begin with. With an associative array, adding and removing items goes like this:
Array.prototype.contains = function(obj)
{
var i = this.length;
while (i--)
{
if (this[i] === obj)
{
return true;
}
}
return false;
}
Array.prototype.add = function(key, value)
{
if(this.contains(key))
this[key] = value;
else
{
this.push(key);
this[key] = value;
}
}
Array.prototype.remove = function(key)
{
for(var i = 0; i < this.length; ++i)
{
if(this[i] == key)
{
this.splice(i, 1);
return;
}
}
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function ForwardAndHideVariables() {
var dictParameters = getUrlVars();
dictParameters.add("mno", "pqr");
dictParameters.add("mno", "stfu");
dictParameters.remove("mno");
for(var i = 0; i < dictParameters.length; i++)
{
var key = dictParameters[i];
var value = dictParameters[key];
alert(key + "=" + value);
}
// And now forward with HTTP-POST
aa_post_to_url("Default.aspx", dictParameters);
}
function aa_post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
// Move the submit function to another variable
// so that it doesn't get written over if a parameter name is 'submit'
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var i = 0; i < params.length; i++)
{
var key = params[i];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_(); // Call the renamed function
}
If, for whatever reason, the delete key is not working (like it wasn't working for me), you can splice it out and then filter the undefined values:
// To cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});
Don’t try and chain them since splice returns removed elements;
By using the "delete" keyword, it will delete the array element from array in JavaScript.
For example,
Consider following statements.
var arrayElementToDelete = new Object();
arrayElementToDelete["id"] = "XERTYB00G1";
arrayElementToDelete["first_name"] = "Employee_one";
arrayElementToDelete["status"] = "Active";
delete arrayElementToDelete["status"];
The last line of the code will remove the array element whose key is "status" from the array.
You can do the following if you want a more functional and elegant approach:
const o = { firstName: "foo", lastName: "bar" };
const { lastName, ...removed } = o;
lastName // bar
removed // { firstName: "foo" }
Note that the value of removed will be undefined if there are no items left in the object.
You can remove an entry from your map by explicitly assigning it to 'undefined'. As in your case:
myArray["lastname"] = undefined;
We can use it as a function too. Angular throws some error if used as a prototype. Thanks #HarpyWar. It helped me solve a problem.
var removeItem = function (object, key, value) {
if (value == undefined)
return;
for (var i in object) {
if (object[i][key] == value) {
object.splice(i, 1);
}
}
};
var collection = [
{ id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
{ id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
{ id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];
removeItem(collection, "id", "87353080-8f49-46b9-9281-162a41ddb8df");
It's very straightforward if you have an Underscore.js dependency in your project -
_.omit(myArray, "lastname")
The only working method for me:
function removeItem (array, value) {
var i = 0;
while (i < array.length) {
if(array[i] === value) {
array.splice(i, 1);
} else {
++i;
}
}
return array;
}
Usage:
var new = removeItem( ["apple","banana", "orange"], "apple");
// ---> ["banana", "orange"]
For "Arrays":
If you know the index:
array.splice(index, 1);
If you know the value:
function removeItem(array, value) {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
The most upvoted answer for delete works well in case of objects but not for the real arrays. If I use delete it removes elements from loops but keeps the element as empty and length of array wont change. This may be a problem in some scenarios.
For example, if I do myArray.toString() on myArray after removal via delete, it creates an empty entry, i.e. ,,.
var myArray = newmyArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
var s = JSON.stringify(myArray);
s.replace(/"lastname[^,}]+,/g, '');
newmyArray = JSON.parse(p);
Without looping/iterates we get the same result.