array push method not working properly - javascript

I am getting the following error for third line:
Can not set property accountName of Undefined
Can anyone help?
var temp = [];
temp.accountId = newData.Account.Id;
temp.accountType = newData.Account.Type;
temp.accountholder.accountName = newData.Account.Name;
finaloutput.push(temp);

set temp.accountholder in advance.
var temp =[];
temp.accountId = newData.Account.Id;
temp.accountType = newData.Account.Type;
temp.accountholder = {};
temp.accountholder.accountName = newData.Account.Name;
finaloutput.push(temp);

Related

Error in my task 4, it seems that .checked and .value doesn't seem to work as intended

Link to Scrimba to check on code : https://scrimba.com/scrim/czvrQJcM
Essentially what should happen is that when the details are added and the button is clicked, the data first gets saved into the object, 'student' and pushed into the array. Then the array is run and the students names are displayed on the page.
I just solve your problem. Look:
At your enrolStudent() function you set the following line:
studentList = studentList.push(student);
So, you should change it to:
studentList.push(student);
This is because the push() method returns the length of the array. So, you don't need to attribute the operation result to the array. The method already updated its own value.
Task4 after the change:
function enrolStudent()
{
let firstnameRef = document.getElementById("fname");
let lastnameRef = document.getElementById("lname");
let studentIdRef = document.getElementById("studentid");
let dateRef = document.getElementById("date");
let courseRef = document.getElementById("course");
let genderRef = document.getElementsByName("gender");
for (let i=0; i < genderRef.length; i++)
{
if (genderRef[i].checked)
{
var genderSelection = genderRef[i];
}
}
let student = new Object();
student.firstName = firstnameRef.value;
student.lastName = lastnameRef.value;
student.id = studentIdRef.value;
student.course = studentIdRef.value;
student.gender = genderSelection.value;
student.date = dateRef.value;
studentList.push(student);
var val = studentList.push(student);
studentEnrolSummaryRef.innerHTML = displayStudents(studentList);
console.log(val);
}
```

javascript - How to get the value of variable as variable with window in an object

key = 'first_name';
// This key might be anyting else
// key = 'last_name';
// key = 'age';
value = 'Ali';
// This value might be anyting else
// value = 'Jones';
// value = '50';
I want to send the value of an object using ajax like this:
key_value = {first_name: 'Ali'};
however the first_name above might change each time, so I tried:
key_value = {key: value};
however I want the value of key which is first_name in this example so I tried to use window
key_value = {window['key']: value};
But it throwed an error:
SyntaxError: missing : after property id
How can I fix this? THANKS
You can try this:
var key_value = {};
key_value[key] = value;
Snippet Example:
var key = 'first_name';
var value = 'Ali';
var key_value = {};
key_value[key] = value;
console.log(key_value);
Why not make use of shorthand property assignment in the object:
var key = 'first_name';
var value = 'abc';
var key_value = {[key]:value};
console.log(key_value);
var jsonVariable = {};
var key='first_name';
var value='Ali';
jsonVariable[key]=value;
Send jsonVariable through Ajax.

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

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>

Why Is My JavaScript Object Throwing An Undefined Error?

I am getting this error in my console:
Uncaught TypeError: Cannot read property 'kbsrc' of undefined
I get this error because I think there may be something wrong with the way I created my JavaScript Object. I have never created an object that is as multidimensional as this one so I am probably screwing up the syntax somewhere. I generate the objects in the mark-up file here:
var kb_work = {}
kb_work['2014'] = {};
kb_work['2014']['kbid'] = ["51","47"];
kb_work['2014']['kbsrc'] = ["images\/images-4.jpeg","images\/imgres-3.jpeg"];
kb_work['2014']['kbtitle'] = ["shalom","Test 6"];
kb_work['2014']['kbmedium'] = ["2x2","Oil"];
kb_work['2014']['kbsize'] = ["2x2","2x6"];
kb_work['2014']['kbdate'] = ["2014","2014"];
kb_work['2013'] = {};
kb_work['2013']['kbid'] = ["55","54","53","52","50"];
kb_work['2013']['kbsrc'] = ["images\/imgres-4.jpeg","images\/imgres-3.jpeg","images\/imgres-1.jpeg","images\/images.jpeg","images\/images-3.jpeg"];
kb_work['2013']['kbtitle'] = ["totally","heheh","Howdy","tickle","hi"];
kb_work['2013']['kbmedium'] = ["oil","oil","2x2","o","oil"];
kb_work['2013']['kbsize'] = ["2x2","2x2","2x2","2x2","2x1"];
kb_work['2013']['kbdate'] = ["2013","2013","2013","2013","2013"];
kb_work['2012'] = {};
kb_work['2012']['kbid'] = ["49"];
kb_work['2012']['kbsrc'] = ["images\/images-2.jpeg"];
kb_work['2012']['kbtitle'] = ["chicked"];
kb_work['2012']['kbmedium'] = ["oil"];
kb_work['2012']['kbsize'] = ["3x4"];
kb_work['2012']['kbdate'] = ["2012"];
Each of these arrays have only one value right now, but will grow as the user adds work. Following this I link to a file, which contains this function (I commented on the specific line) that the TypeError refers to:
function changeGal(gallery_year) {
$("#gallery-control-bar").fadeOut(t);
$("#gallery-image").fadeOut(t);
$("#info").fadeOut(t);
$("#gallery-viewer").fadeOut(t);
//this is where the script chokes up referring to "currentImg" which is 0 and refers to the first value in the array "['2014']['kbsrc']".
$("#gallery-image").html("<img src='" + kb_work[gallery_year]['kbsrc'][currentImg] + "'>");
$("#gallery-title").html(kb_work[gallery_year]['kbtitle'][currentImg]);
$("#gallery-medium").html(kb_work[gallery_year]['kbmedium'][currentImg]);
$("#gallery-size").html(kb_work[gallery_year]['kbsize'][currentImg]);
$("#gallery-date").html(kb_work[gallery_year]['kbdate'][currentImg]);
$("#gallery-control-bar").delay(t + d).fadeIn(t);
$("#gallery-image").delay(t + d).fadeIn(t);
$("#info").delay(t + d).fadeIn(t);
var userCurrent = currentImg + 1;
var userTotal = kb_work[gallery_year][0].length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
Any thoughts to why it cannot reference the value?
I think you need
$("#gallery-image").html("<img src='" + kb_work[gallery_year][gallery_year + '.kbsrc'][currentImg] + "'>");
because it looks like gallery_year is a year value like 2013, but the key is a concatenation string value like 2013.kbsrc
There is another problem with your structure because kb_work[year] should be an obeject not an array, again the second level of keys need not have the year again.
So the structure can be updated to
var kb_work = {}
kb_work['2014'] = {};
kb_work['2014']['kbid'] = ["46"];
kb_work['2014']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2014']['kbtitle'] = ["Test 5"];
kb_work['2014']['kbmedium'] = ["Oil"];
kb_work['2014']['kbsize'] = ["2x5"];
kb_work['2014']['kbdate'] = ["2014"];
kb_work['2013'] = {};
kb_work['2013']['kbid'] = ["44"];
kb_work['2013']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2013']['kbtitle'] = ["Test 3"];
kb_work['2013']['kbmedium'] = ["Oil"];
kb_work['2013']['kbsize'] = ["2x1"];
kb_work['2013']['kbdate'] = ["2013"];
kb_work['2012'] = {};
kb_work['2012']['kbid'] = ["45"];
kb_work['2012']['kbsrc'] = ["images\/screen shot 2014-03-05 at 11.31.04 pm.png"];
kb_work['2012']['kbtitle'] = ["Test 4"];
kb_work['2012']['kbmedium'] = ["Oil"];
kb_work['2012']['kbsize'] = ["2x3"];
kb_work['2012']['kbdate'] = ["2012"];
then to access it
kb_work[gallery_year]['kbsrc'][currentImg]
Your nesting shows that you think this works differently to how it actually works...
var kb_work = {}
kb_work['2014'] = new Array();
kb_work['2014.kbid'] = ["46"];
Actually results in an object like this: {"2014":[],"2014.kbid":["46"]}
I believe you want this:
var kb_work = {
'2014': [
{ 'kbid': ["46"] }
]
};
Which results in an object like this: {"2014":[{"kbid":["46"]}]}
Now you can access:
kb_work['2014'][0].kbid[0] // 46
And you can pass in the year as a variable containing the string and the 0s can be a variable containing the index.
You can add multiple lines like this:
var kb_work = {
'2014': [
{ 'kbid': ["46"] },
{ 'kbid': ["62"] },
{ 'kbid': ["90"] }
]
};

Is it possible to replace sub object with other object in main object?

I want to replace the sub object with some other object in main object.
ex:
var mianobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var newsubobj = {"n":"8888","g":"9999"}
console.log(mainobj.a.aa)
// this gives the sub object --> {"aaa":"0000","bbb":"1111"}
I want to replace this object with newsubobj.
I need the result as ::
console.log(mainobj);
// {"a":{"aa":{"n":"8888","g":"9999"}},"b":"222","c":"333"}
Thanks in advance.
Why you don't do it like that:
mainobj.a.aa = newsubobj
?
Ah, now we're getting somewhere. To update your question you have:
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var subobjpath = "a.aa"; // this needs to be a string
var newsubobj = {"n":"8888","g":"9999"}
and you want to use subobjpath to replace a part of mainobj with newsubobj.
You can do so using code like this:
var path = subobjpath.split('.');
var obj = mainobj;
for(var idx=0; idx < path.length-1;idx++) obj = mainobj[path[idx]];
obj[path[path.length-1]] = newsubobj;
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"};
var newsubobj = {"n":"8888","g":"9999"};
mainobj.a.aa = newsubobj;
console.log(mainobj);

Categories

Resources