This question already has answers here:
Convert javascript object or array to json for ajax data
(2 answers)
Closed 8 years ago.
I now this question has been asked before but I am trying to work this out since this morning and I can't get it right.
I have a global variable named items
I have a .ajax request that I need to send the contents of the items array
Items is like this
items = new Array();
for (var i = 0; i < 10; i++)
{
//just populating the list
var item = [];
item['some_stuff'] = 'string';
item['some_int'] = 373;
items.push(item);
}
//here is the request
if (items.length > 0)
{
$.ajax({
type : "POST",
url : "/grad1/adaugaComanda.php",
data : { "stuff" : items},
success : function (data){
alert(data);
// window.location = '/dashboard.php?categ=5&sel=1';
}
});
}
//
The request is executed but data is not sent. I tried to use JSON.stringify on the array but it returns empty ([[]]).
Any ideas what I am doing wrong ?
//just populating the list
var item;
This declares a variable called item but does not give it a value to it so it is undefined
item['some_stuff'] = 'string';
This attempts to assign a value to the some_stuff property of undefined. This isn't allowed, so JS will throw an exception and script execution will cease.
You aren't making a request at all, because your script isn't getting far enough to do that.
You need to assign an object to item:
var item = {}
You have edited your question so your code now reads:
var item = [];
You still need to use a plain object here ({} not []). Array objects should only have numeric indexes. jQuery will ignore named properties on an array when serializing it.
Related
This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I am getting the error
Cannot read property 'billingDate' of undefined
installment here is undefined
response.detailsResponse.installment.billingDate
I want to use hasOwnProperty but in a dynamic way, like I pass the path and the object (to check against) to a function, it does the following checks and return true or false.
function checkProperty(path, obj){
//assuming path = response.detailsResponse.installment.billingDate
//assuming obj = response [a json/object]
//check if response.detailsResponse exists
//then check if response.detailsResponse.installment exists
//then check if response.detailsResponse.installment.billingDate exists
}
The path length/keys can vary.
The code has to be optimized and generic.
You can rewrite the function in the following way
function checkProperty(path,obj){
splittedarr = path.split('.');
var tempObj = obj;
for(var i=1; i<splittedarr.length; i++){
if(typeof tempObj[splittedarr[i]] === 'undefined'){
return false;
}else{
tempObj = tempObj[splittedarr[i]];
}
}
return true;
}
Starting from index 1 as in accordance to your example it seems like response in response.detailsResponse.installment.billingDate for path is same as the obj passed to the function.
I have some JSON returning from my server that looks like this
[{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"}]
I then handle this by using
var data = JSON.parse(json);
then, once doing this, I call this in a loop
data.item(i);
or using the function
data.splice(i, 1);
giving me the error
data.item is not a function
or
data.splice is not a function
I'm pretty certain that this is because it is not a true javascript array, but I haven't found anything that has told me how to convert it to one
EDIT I was actually looking for the .item() function used in NodeList (from things like getElementByClassName) however, this does not solve my issue with .splice
Your JSON is invalid - it needs commas separating the objects:
[{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"}]
Parse the JSON like you were:
var data = JSON.parse(json);
And to access each object, use the index of the array:
var element1 = data[0]; // first element
var element2 = data[1]; // second element
etc.
And to access the values in the objects:
var name1 = data[0].name1; // value1
or even, since you've already defined the element1 variable:
var name1 = element1.name1;
If you're using a loop:
for (var i = 0, l = arr.length; i < l; i++) {
console.log(data[i]);
}
Once you've run data = JSON.parse(json), you can verify that data is an array using either data instanceof Array or Array.isArray(data).
In this case, both should be true, because you do have an array. JS arrays simply don't have an item method (that is, Array.prototype does not have a property item that is set to a function, or in fact, an item property at all), so you're trying to call something that does not exist.
To access an element from an array, you use the arr[n] syntax with a number. This is how you retrieve elements, not calling item.
While parsing, if your JSON is invalid, an exception will be thrown. You should wrap the JSON.parse call in try { ... } catch block to safely handle that.
All together, your code would look something like:
try {
var data = JSON.parse(json);
if (data && data.length) { // make sure data is a real thing and has some items
for (var i = 0; i < data.length; ++i) {
console.log(data[i]); // using [] to access the element
}
}
} catch (e) {
console.error('Parsing JSON failed:', e);
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am trying to get the first value for an object like:
{
"_id":"123",
"list":{"56":{"name":"Great ","amount":100,"place":"Town"},"57":{"name":"Great 2","amount":200,"place":"City"}},
"pop":[2,3]
}
This is 1 object of around 100 or so. I am trying to get the amount from the first value of list property in each of the 100 objects ? i.e. so above it would be 100
How would I do that ? I am using underscore JS ?
You are defining list as object . Object properties are in order of they defined, but we cannot trust its order . I think there is Chrome bug about it https://code.google.com/p/v8/issues/detail?id=164
the following first method gives first element from list object , this function will works most cases , if object is empty it will return undefined value.
var data = {
"_id":"123",
"list":{
"56":{"name":"Great ","amount":100,"place":"Town"},
"57":{"name":"Great 2","amount":200,"place":"City"}
},
"pop":[2,3]
};
function first( data ){
for ( var i in data ){
if ( data.hasOwnProperty(i) ) break;
}
return data.hasOwnProperty(i) ? data[i] : undefined;
}
first( data.list ).amount;
If you want to keep order of list .. define them as Array . example
var data = {
"_id":"123",
"list":[
{"id" : "56" ,"name":"Great ","amount":100,"place":"Town"},
{"id" : "57" ,"name":"Great 2","amount":200,"place":"City"}
],
"pop":[2,3]
};
and access them as data.list[0]
You can try this
function getFirstAmount(obj){
for(var key in obj){
return obj[key].amount;
}
}
If you need to get all keys, you can try this
function getAmounts(obj){
var amounts = [];
var i = 0;
for(var key in obj){
amounts[i] = obj[key].amount;
i++;
}
}
return amounts;
}
//call function
var firstAmount = getFirstAmount(obj.list);
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
In javascript you have Arrays (lists) and Objects (maps).
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
Array.indexOf(element) returns -1 if element is not found, otherwise returns its index