JSON parsing not working in jQuery [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have a text field with id search_json on a form that contains:
{"standard_id":"2","attribute1":["","Stan"],"attribute2":[""],"attribute3":["","Air Force"],"attribute4":["","Bob"],"selected_index":3}
Upon some event, call it a button click, I want to:
1) Read in that JSON and parse it into an object:
search_json = $.parseJSON($("#search_json").val())
2) Remove "attribute1" from the object
delete search_json["attribute1"]
3) Write the JSON back out to the text field:
$("#search_json").val(JSON.stringify(search_json))
I'm kind of surprised it's not working, though. The delete call does nothing. As a matter of fact,
search_json.hasOwnProperty("attribute1")
returns false. And yet I can log the object to console and it is indeed an object with those values. What is going wrong here?
UPDATE: Actually,
search_json.hasOwnProperty("attribute1")
DOES work. But, if I get the attribute name from another text field, like so:
attribute_name = $("#attribute_name").attr("id")
and:
console.log attribute_name
shows "attribute1", then this does NOT work:
search_json.hasOwnProperty(attribute_name)
returns FALSE. Mystifying.

I don't get it. I'm using your fiddle code and everything is correct
http://jsfiddle.net/ddQbe/1/
The final object is:
attribute2: Array[1]
attribute3: Array[2]
attribute4: Array[2]
selected_index: 3
standard_id: "2"
attribute1 was delete correclty

I would try creating a new result_json object.
var result_json = {};
for (var prop in search_json) {
if (prop !== 'attribute1') {
result_json[prop] = search_json[prop];
}
}
$("#search_json").val(JSON.stringify(result_json));

Related

Pushing data to an array inside another array with Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I made an array for a raffle system using node.js and discord.js which has this data set.
[{"author":"Name","rafflename":"RAFFLE","amount":"10","entries":"[]"}]
When someone tries to enter the raffle I'd like to make another JSON array inside the entries tag.
The problem i face is when i use raffles[0].entries.push({ 'username': 'example', 'user_id': '1' });
It returns an error: raffles[0].entries.push is not a function
I assume this is because it is looking for the array raffles[0].entries.push which does not exist. But I've only ever used the push command. So I am not sure how to fix this issue.
Move your entries [] out of double quotes, i.e. Use "entries" :[]
You are trying to push to a string instead of array
You have to cast entries to Array first.
const raffles = [{"author":"Name","rafflename":"RAFFLE","amount":"10","entries":"[]"}]
// cast entries to Array
raffles[0].entries = JSON.parse(raffles[0].entries)
// now you can push them
raffles[0].entries.push('test')
console.log(raffles)
It isn't working because you have "" around the properties inside of your object. you can fix this by either removing the "" or doing this:
raffles[0]['entries'].push(//your code here);
When properties of an object are strings (i.e. when they have quotes around them) you must access that property using "dot notation"
eg:
var object = {"property":"five"};
console.log(object["property"]); //prints 'five'
console.log(object.property); //throws an error
Format Your Array according to #Bibberty Comment and do operation
raffles=rafale=[{"author":"Name","rafflename":"RAFFLE","amount":10,"entries":[]}]
raffles[0].entries.push({ 'username': 'example', 'user_id': 1 });
console.log(raffles)

Cannot read property 'teacherId' of undefined when calling the array of object [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
var teacherArray=[];
I have created an array variable.
I am creating an array with the key and value. and pushing these data to the teacherArray.
random={
teacherId:TeacherId,
day:day,
periodCount:period,
class:Studentclass,
section:Studentsection,
startTime:schoolStartTime,
endTime:schoolEndTime
};
teacherArray.push(random);
console.log(teacherArray);
In the console I am able to see the created array. But when the submit button clicked i am calling the array like
teacherLength=teacherArray.length;
for (let k=0;k<=teacherLength;k++)
{
var teachId=teacherArray[k].teacherId;
console.log(teachId);
}
In the console displays the teacherId, but next line shows the error as
TypeError: Cannot read property 'teacherId' of undefined
Arrays are zero index based. So when you write k<=teacherLength you are requesting more than what array have. That should be changed to
k<teacherLength
Arrays are 0 indexed. You are having,
for (let k=0;k<=teacherLength;k++)
Make it,
for (let k=0;k<teacherLength;k++)
Your code is reading an extra item, you need to replace
for (let k=0;k<=teacherLength;k++)
with
for (let k=0;k<teacherLength;k++) //notice < instead of <=

Need Array inside other Array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
For some reason I need to push an Array inside other array.
For example,
var a = ["Test1", 1];
var b = ["Test2", 2];
var c = [];
c.push(a);
c.push(b);
alert(c);
For this code I need the following output,
["Test1", 1],["Test2", 2]
But what I am getting is
Test1,1,Test2,2
Any help will be highly appreciable.
You've already done it correctly: c.push(a) and c.push(b) work, but you don't want to use alert() for debugging.
Though it might be more convenient since you don't have to open up a console, it's going to give you output that is inconsistent with the actual structure of the data because using alert(x) converts whatever x is to a string.
Always use console.log(). Had you done that in this case, you would have seen something like this in the console:
Demo

How can I get the contents of an array out of an object? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a variable which looks like this when I log it:
console.log(msg)
["The Email must be at least 10 characters long."]
I thought this meant that the text is inside an array as the 1st and only element. However
when I try to get the first element it gives me:
console.log(msg.[0]))
SyntaxError: Unexpected token [
How can I extract the text from the msg variable?
To get the contents of an array:
for (var i = 0; i < yourArray.length; i++) {
console.log(yourArray[i]);
}
To get the contents of an object:
for (var obj in myObject) {
console.log(obj);
}
You're syntax is wrong, instead you need:
console.log(msg[0]))
[] accessors are used for array access, or to access an object property via a string myObj["value"]
. accessors are used for fields when you know the name so you could use myObj.value
simply remove the . when accessing individual array elements.
therefore it becomes :
console.log(msg[0]);
Take the dot in msg.[0] out.
console.log(msg[0])
should retrieve your text correctly.

How to add property to a global Javascript object inside a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am tying to add a property to a JS object inside a function. I can do it outside but not inside. Please explain. Sorry. I am missing something very basic here.
var newobj = {'prop1' : 12, 'prop2' : 25};
myfunc(newobj);
function myfunc(someobj) {
someobj.prop3 = 45;
}
This gives a syntax error.
Chances are something else is interfering because it works for me.
If you dump newobj before the function call you get:
{"prop1":12,"prop2":25}
And after the function call:
{"prop1":12,"prop2":25,"prop3":45}
As you can see, the new property has been added.
I would suggest either looking at what you have more closesly (make sure you're not copying the value and then passing it) or add some console.log call in your code as it goes through. You can also, in most of the browsers, use the debugger to step through the code to see where it may be fouled.

Categories

Resources