JSON element pushing into array in Javascript [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 5 years ago.
Improve this question
I am looking to access a HTML element's data (a JSON record) and push it into an array in JavaScript.
The HTML is:
<td class="card-holder" data-card="{"id":0,"type":"Wildcard","image":"wildcard.png","strength":0,"type_image":"wildcard.png","region_owned_adder":0}">
<img id="card-image-0" src="/img/wildcard.png" class="card-exchange">
<input class="cards-checkbox" type="checkbox" id="card-0" name="cards_to_exchange[]" value="id=" 0""="">
<label for="cards_to_exchange"></label>
</td>
I have a number of these on my page. I read each in a loop and select some to push into an array like this:
var cards = [];
$('.card-exchange').each(function() {
if ($(this).find('input[name="cards_to_exchange[]"]').is(':checked')) {
var parseCard = JSON.parse(thisElement.data('card'));
cards.push(parseCard);
}
});
But this is showing me [] after the loop:
console.log(cards);
This shows the data OK:
console.log(thisElement.data('card'));
How do I read the string and push it into array as object? Thanks.

You're using .find() on an <img>, which has no descendants.
Use .next() instead to get its <input> sibling.
Also, you can use .filter() and then .map() to clean it up a little.
var cards = $('.card-exchange').filter(function() {
return $(this).next().is(':checked');
}).map(function() {
return JSON.parse(thisElement.data('card'));
}).toArray();
Though I'm not sure what thisElement is referring to.
You could even shorten it a little more.
var cards = $('.card-exchange + input:checked')
.prev()
.map(function() {
return JSON.parse(thisElement.data('card'));
});

Related

Return object result [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 26 days ago.
Improve this question
I need to get the result of this object, I've tried json.count(id_reported) and json['count(id_reported)'] but none worked.
const json = {
'count(id_reported)': 21
};
//console.log(json.count(id_reported));
console.log(json['count(id_reported)']);
In Javascript, Typescript and so in Express in the end, its easy to handle such things.
var myObject = {
'count': 21
}
myObject = JSON.parse(myObject);
console.log(myObject.count);
The JSON.parse is only needed, if you object is a string. Is it a Javascript object you do not need to parse.
The count(id_reported) part I don't understand. If your object looks like this in the end:
{
count(1): 1,
count(2): 2,
}
and you don't know the structure at all you can use a for loop:
for (let data in myObject) {
console.log(data); // data will be the key; so count(1) as example
}
See the in keyword in the for loop. This will give you the key. The on keyword otherwise gives the object in an array as example.

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 <=

Array[key].push Is Not Defined in JavaScript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
When trying to push items to an array in javascripts it gives an error, the following pseudo code illustrate what is happening:
var data = new Array();
for(...) {
data[key].push(item[i]);
}
It is showing the following error:
Cannot read property 'push' of undefined
Thanks
If you need a 2d array, you have to initialize each element of the outer array to be an array.
// Have to check every array item, if it's not an array already, make it so
for(...) {
if (!data[key]) {
data[key] = [];
}
data[key].push(item[i]);
}
You could always do the following if you know the number of inner arrays you need:
var data = [[],[],[],[],[],[]];
In your example, since they variable name is key, I'm assuming you actually want an object of arrays. If you know the keys ahead of time, you can use the following literal.
var data = {
myKey1: [],
myKey2: []
}

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.

JSON parsing not working in jQuery [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 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));

Categories

Resources