remove entry from javascript array - javascript

I have created an array:
myarray = new Array();
myarray['test_a'] = "test a";
myarray['test_b'] = "test b";
Now I would like to remove the entry with index "test_b". I tried this way:
var del = "test_b";
for(key in myarray){
if(key==del){
myarray.splice(key,1);
}
}
However it does not work. No error. I just checked in firebug the entries for the array and mentioned that "test_b" still exists. What is wrong? Thanks for help.

Arrays are meant to have numeric indices, you want an object, then you can simply use delete:
var obj = {};
obj.test_a = "test a";
obj.test_b = "test b";
var del = "test_b";
delete obj[del];
console.log(obj); //=> { test_a: "test_a" }

splice works on numerical index, what you have is that you have added a property to the array object. You can just do a delete to delete the property from the array object.
delete myarray[del];
Demo
if you are just defining properties on an array and using it just as an object then better consider using an object instead of creating an array to store properties

Related

Weird data lose in javascript while converting Array into Object

I was just working with JavaScript objects and found this which i cant figure out . I created an array with few values and trying to convert that array into object using spread and new in JavaScript but for my surprise only the first value in the array is been put into the object with its type .
I have no need what exactly is happening in background
let array = [1970,1,1]
let object = new Object(array)
console.log(object)
Output :
NumberĀ {1970}
I was expecting {1970 , 1 , 1} object but actual output is
NumberĀ {1970}
to convert array to object use Object.assign
Object.assign({},[1970,1,1])
or you can populate the object with the array elements
let array = [1970,1,1];
var obj = new Object();
Array.prototype.push.apply(obj, array);
console.log(obj);
The closest thing you could do is:
const object = {...array}
Which will give you the output:
{0: 1970, 1:1, 2:1}
You can try with Object.assign()
let array = [1970,1,1];
let object = Object.assign({}, array);
console.log(object);
It works in the Chrome (Version 75).
Check the following code, if in case you are expecting the following behavior.
CODE:
let array = [1970,1,1];
let obj = {}, i = 0;
for(var element in array) obj[i++] = array[element];
console.log(obj);

Insert a new object in Array of object

I have an Array List.
dataList = []
I want to insert object in array, So I tried this,
dataList.concat([{"name":"BOB", "value":"1"}])
// [{"name":"BOB", "value":"1"}]
but when I insert 2nd object in the same array.
dataList.concat([{"name":"Joe", "value":"2"}])
// [{"name":"Joe", "value":"2"},{"name":"Joe", "value":"2"}]
after inserting second array it replaces first object also.
where am I wrong?, Please help.
Simply use push function
var dataList = [];
dataList.push({
"name": "BOB",
"value": "1"
});
//Pushing second object
dataList.push({
"name": "Joe",
"value": "2"
})
console.log(dataList)
To push a value in an array, you will have to use array.push. array.concat does not adds new item. it merges 2 array and return a third array. So your code:
dataList.concat([{"name":"BOB", "value":"1"}])
does not do anything.
var dataList = []
dataList.concat([{"name":"BOB", "value":"1"}])
console.log(dataList)
As per the behavior, your code should look something like this:
var dataList = []
var obj = [{"name":"BOB", "value":"1"}];
dataList = dataList.concat(obj)
obj[0].value = 2;
dataList = dataList.concat(obj)
console.log(dataList)
The reason both the objects are being affected is because, objects are copied/assigned using reference. So a variable will hold a memory location and any changes to it will be reflected to this location. So if you have more than 1 variable holding this reference, it will also get updated.
So how should you achieve this?
var dataList = []
var obj = {"name":"BOB", "value":"1"};
dataList = dataList.concat(obj)
var obj2 = Object.assign({}, obj)
obj2.value = 2;
dataList = dataList.concat(obj2)
console.log(dataList)
But still using Array.concat is wrong. It is not intended to be used like this.
var dataList = []
var obj = {"name":"BOB", "value":"1"};
dataList.push(obj)
var obj2 = Object.assign({}, obj)
obj2.value = 2;
dataList.push(obj2)
console.log(dataList)
References:
How to append something to an array?
Why does changing an Array in JavaScript affect copies of the array?
How do I correctly clone a JavaScript object?
Object.assign - MDN

.match Array value is undefined

I'm calling the .string method on a string and setting that equal to another variable. It returns an array with the [match value, index, and input].
When I try to refer to the second element in the array, it comes back as undefined. Can someone tell me why that is? Heres my code:
var str = "hello world"
var matchArray = str.match("ell");
=>matchArray = ["ell",index:1,input:"hello world"]
var index = matchArray[1];
console.log(index);
=>undefined
Thanks in advance.
var str = "hello world"
var matchArray = str.match("ell");
matchArray is an Array but in javascript as we know we can set properties in array as well as it's an object.
In the above case, matchArray has only the mathces in the array. but the other properties such as index and input are in the object.
If you do console.dir(matchArray) you would get the properties as well.
So to access those properties use object's notation like matchArray.index or matchArray.input
JavaScript is an interesting language. Although the matchArray object is indeed an array, in JS you can add new members to any object. So, matchArray is an array of length 1, but it also has the members index and input defined on it. Try this:
...
console.log(matchArray.index);
console.log(matchArray.input);
We could define a similar object from scratch like this:
var hybridObj = [ "ell" ]; // It's an array
hybridObj.index = 1; // With props
hybridObj.input = "hello world";

Iterate through a json object

Here is my object
var myObject = {"HardGood":362,"Music":2};
console.log(myObject[0]); // undefined? instead of "Hardwood 362"
What am I doing wrong?
myObject is an object not an array, so using [0] will indeed be undefined.
Use myObject.HardGood or myObject.Music to get the value or that property
Code
console.log(myObject.HardGood); // will output 362
console.log(myObject.Music); // will output 2
UPDATE
var objects = [
{
"title": "HardGood"
"type": "362"
},
{
"title": "Music"
"type": "2"
}
];
console.log(objects[0].title); // output HardGood
console.log(objects[1].type); // output 2
You should call the first element in an object like this: myObject.key and your key is HardGood.
In arrays it's done like this:
var _Array = [];
_Array .push('x1'); //pushing in array
_Array .push('x2');
console.log(_Array[0]); // getting the first element in that array
Update: if you want to get it dynamically:
var myObject = {"HardGood":362,"Music":2};
for(var key in myObject){
console.log(key +':'+myObject[key]);
}
You have to access JSON object property with . Like below
var myObject = {"HardGood":362,"Music":2};
console.log(myObject.HardGood); //362
Useful links Have a look at below links to understand it better.
Javascript-property-access-dot-notation-vs-brackets
JS-dot-notation-vs-bracket-notation
MDN - OperatorsProperty_Accessors

jQuery .data() remove item from stored array

I am using the .data() function in jQuery to store an array as per below:
var myArray = {};
myArray[0] = {};
myArray[0][0] = "test00";
myArray[0][1] = "test01";
myArray[1] = {};
myArray[1][0] = "test10";
myArray[1][1] = "test11";
$('#datastorage').data("testname". myArray);
I want to remove only one item (myArray[0]) from the "testname" and keep the rest.
The below does not work:
$('#datastorage').removeData("testname").removeData(0);
I believe jQuery stored the array in a form of a plain object (the test $.isPlainObject() comes back true)
I am now trying to use the function .not() to remove the element...
Since the original object is an array, what's actually stored is just a reference to the original data, so any modification you make is reflected in every reference to that array, including the one stored in .data().
So you can just remove the element from the array:
$('#datastorage').data("testname").shift();
or if you want more flexibility on which elements are removed, use .splice().
$('#datastorage').data("testname").splice(0, 1);
or if you've still got access to myArray:
myArray.shift();
There's no need to put the array back into .data() - any of the above will modify both myArray and whatever's already in .data() - they're the same array!.
The same would apply if the data was an object, but not if it's a primitive type.
You'll have to get the array out, remove from it, and then put it back.
var a = $('#datastorage').data('testname');
a.splice(0,1); // remove 1 item from position 0
$('#datastorage').data('testname', a);
try this code
var myArray = []; // myArray is an Array, not an object
myArray[0] = {};
myArray[0][0] = "test00";
myArray[0][1] = "test01";
myArray[1] = {};
myArray[1][0] = "test10";
myArray[1][1] = "test11";
$('#datastorage').data("testname", myArray);
console.log($('#datastorage').data("testname"));
$('#datastorage').data("testname", myArray.slice(1));
console.log($('#datastorage').data("testname"));
example fiddle: http://jsfiddle.net/nNg68/

Categories