Cannot read property 'push' of undefined How to solve? - javascript

var item_data = [];
var index = 0;
var data = JSON.parse([{"A":"0","B":"100","C":"0","D":"0"}]);
item_data[index].push(data);
console.log(item_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Anyone can please help me why it appearing script error in my system it appearing
Uncaught TypeError: item_data[index].push is not a function
How can I solve this issue?

Use assignment operator (=) to insert any item at specific position of an array by using index like:
item_data[index] = data;
OR: If you want to use push() you do not need to use index at all. Because
The push() method adds one or more elements to the end of an array and returns the new length of the array.
item_data.push(data);
var item_data = [];
var index = 0;
var data = JSON.parse('[{"A":"0","B":"100","C":"0","D":"0"}]');
item_data[index] = data;
console.log(item_data);

Change the JSON to string and push that into the array item_data.
var item_data = [];
var index = 0;
var data = JSON.stringify([{"A":"0","B":"100","C":"0","D":"0"}]);
item_data.push(data);
console.log(item_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Getting error .append is not a function

I am trying to split up a string on /* and then to split up those segments on */
So that I can separate out all of the comments as I want this code to be able to take all of the comments out of the string and then put it back together.
The problem is though I keep getting this .append error which I am pretty sure is because I have made a silly syntax error but I am struggling to find it and any help would be greatly appreciated.
JS
contents = "if for /* else */ . = == === /* return */ function"
var start = /\/\*/gi;
var end = /\*\//gi;
var commentsRemovedSec2 = [];
var commentsRemovedSec1 = contents.split(start);
console.log(commentsRemovedSec1);
for (var i = 0; i < commentsRemovedSec1.length; i++) {
var z = ""
var x = commentsRemovedSec1[i]
var y = x.split(start)
z = y[0]
commentsRemovedSec2.append(z);
};
console.log(commentsRemovedSec2);
Unfortunately .append() isn't an Array method.
Instead use the Array method .push().
commentsRemovedSec2.push(z)
The push() method adds one or more elements to the end of an array and
returns the new length of the array. MDN

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
Michał

Javascript & jQuery push array to object based on custom attribute

Problem
There are a couple of HTML tags with classes as follows
<span class=​"keyword" column-name=​"Product Group">​Outdoors</span>​
<span class=​"keyword" column-name=​"Material Code">​10001003​</span>​
<span class=​"keyword" column-name=​"Material Code">​10001000​</span>​
All the span needs to be iterated through and a new object would be created with the column-name attribute as its property and the relevant text passed into an array.
Code So Far
I am using the below code but the array passed consists of all the text from the span
var searchCriteria = {};
var keyword = [];
$('.keyword').each(function(index, elem) {
col = $(elem).attr('column-name');
keyword.push($(elem).text());
searchCriteria[col] = (keyword);
});
console.log(searchCriteria);
The above code prepares the object as
{
Material Code: ['Outdoors', '10001003', '10001000']
Product Group: ['Outdoors', '10001003', '10001000']
}
Result Expected
The result of the object which I am expecting is
{
Material Code: ['10001003', '10001000']
Product Group: ['Outdoors']
}
JS Fiddle
Here is a JSFiddle of the same - http://jsfiddle.net/illuminatus/0g0uau4v/2/
Would appreciate any help!
When you use searchCriteria[col] = (keyword);, it does not copy the keyword array. It just stores pointer to that array. So, if you update keyword after assigning it to some variable, it'll also get updated as both of them points to the same array. If you want to copy array you may use .slice() on array. But here it is not needed.
Use the following code instead
var searchCriteria = {};
$('.keyword').each(function(index, elem) {
col = $(elem).attr('column-name');
if ( !Array.isArray(searchCriteria[col]) )
searchCriteria[col] = [];
searchCriteria[col].push($(elem).text());
});
console.log(searchCriteria);
http://jsfiddle.net/0g0uau4v/3/
You can't use the same array as the value for each column. Instead, create a new array each time you encounter a new column, or simply append the value to the existing array if the column-name already exists:
$(function() {
var searchCriteria = {};
$('.keyword').each(function(index, elem) {
var col = $(elem).attr('column-name');
var keyword = searchCriteria[col] ? searchCriteria[col] : [];
keyword.push($(elem).text());
searchCriteria[col] = (keyword);
});
$("#result").text("Result: " + JSON.stringify(searchCriteria));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="keyword" column-name="Product Group">Outdoors</span>
<span class="keyword" column-name="Material Code">10001003</span>
<span class="keyword" column-name="Material Code">10001000</span>
<div id="result"></div>
That was becoz, you were using same updated array for all.
var searchCriteria = {};
var keyword = [];
$('.keyword').each(function(index, elem) {
col = $(elem).attr('column-name');
if( !searchCriteria[col])
searchCriteria[col] = [];
searchCriteria[col].push($(elem).text());
});
console.log(searchCriteria);
Here in this code im searching for, if property doesn't exist . Then make that index as array. And futher you push elements.
Working fiddle
You can instead do this
var searchCriteria = {};
$('.keyword').each(function(){
var key = $(this).attr("column-name");
var value = $('[column-name='+key+']').map(function(){return $(this).text()}).get();
if(!searchCriteria.hasOwnProperty(key)) searchCriteria[key] = value;
});

cannot set property of multidimensional javascript array

My JavaScript code is this:
var i=0;
var ret=[];
ret[i][0]=newID;
ret[i][1]=jobTitle;
ret[i][2]=jobText;
ret[i][3]=jobEmail;
ret[i][4]=jobOrder;
These are all strings and all have value.
I'm getting the error:
"Uncaught TypeError: Cannot set property '0' of undefined" on the
first assignment: ret[i][0]=newID;
Also error at jsfiddle
http://jsfiddle.net/Zf9rE/2/
what am I doing wrong?
You must create ret[i] before you try to add elements to it:
var i=0;
var ret=[];
ret[i] = []; // define ret[i]
ret[i][0]=newID;
ret[i][1]=jobTitle;
ret[i][2]=jobText;
ret[i][3]=jobEmail;
ret[i][4]=jobOrder;
Updated fiddle
Unless there is a reason to hard code the array indexes, you might prefer to either create an array literal (as #Rocket shows in the comments) or use Array.prototype.push():
ret[i].push(newID);
ret[i].push(jobTitle);
Another aproach:
var jobTitle="j title";
var jobText = "j desc";
var jobEmail="jemail";
var jobOrder="j order";
var newID="3";
var i=0;
var ret = new Array();
var matrix = new Array()
ret[0]=newID;
ret[1]=jobTitle;
ret[2]=jobText;
ret[3]=jobEmail;
ret[4]=jobOrder;
matrix[i] = ret;
console.log(matrix[0][0]);
Fiddle: http://jsfiddle.net/robertrozas/Zf9rE/6/

javascript copying array to another

i have the following code snippet, where inside for loop the value to contain is not getting assigned, is this is the proper way to copy array to other.??
as here
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var m=grpNameArr.length;
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(m-1);ii++)
{
contain[ii] = groupCn[ii];
cmds[ii] = grpNameArr[ii];
}
If you want to clone an array you can use slice() method as mentioned in this page:
http://www.hardcode.nl/subcategory_1/article_414-copy-or-clone-javascript-array-object
var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
your array declaration is wrong , it should be like :-
var groupcn=["All","All","All","All"];
var grpNameArr=["abc","def","ghi"];
you can use :
var contain=groupcn.concat();
var cmds=grpNameArray.concat();
So, after your edit, I see your problem was that you has some typo's in your variable names.
Replace:
var grpNameArr = groupParm.split("#");
var groupcn= groupCondtn.split("&");
With:
var grpNameArr = groupParam.split("#");
// ^ Missing `a` and `r`.
var groupCn= groupCondition.split("&");
// ^ Capital C ^ Missing `i`'s and `o`.
Old Answer
These 2 lines:
var groupcn = All,All,All,All;
var grpNameArr = abc,def,ghi;
Are probably your problem.
What you're doing there is assigning the variable All to a new variable groupcn, then declaring All as a new variable, 3 times.
var groupcn=All,
All, // new variable with the name `All`
All, // new variable with the name `All`
All; // new variable with the name `All`. These 3 override `All`
You'll need to initialize them like this:
var groupcn = [All,All,All,All];
var grpNameArr = [abc,def,ghi];
Other than that, assuming m is the length of groupcn, the code should work.
However, a shorter solution is to copy the arrays like this:
var contain = groupcn.slice();
var cmds = grpNameArr.slice();
Following mistakes were in the code
Using one loop for both the arrays. Since there length is not same two different loops should be used.
There was typo mistake in groupcn variable.
Check this code
<!DOCTYPE html>
<html>
<script>
function chk()
{
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(groupcn.length-1);ii++)
contain[ii] = groupcn[ii];
for(ii=0;ii<(grpNameArr.length-1);ii++)
cmds[ii] = grpNameArr[ii];
alert("groupcn = "+contain);
alert("grpNameArr = "+cmds);
}
</script>
<body onload="chk()">
</body>

Categories

Resources