Sending an "associative array" via POST from AngularJS - javascript

I've got an 'filter' object like
{
name: 'text',
value: 'xxx',
field: 'firstname'
}
which represents a filter for a field and is updated when I change values of input fields.
I try to store this in an array in the following way:
$scope.active_filters[filter.field] = filter;
So that I know on which field I got which filter.
The filtering should happen on server side and so I'm trying to send this array to my API.
$http.post(url, $scope.active_filters)
As I can see in Chrome I've got an array with the desired element in it but length 0
[status: Object]
length: 0
status: Object
field: "status"
name: "text"
value: "x"
__proto__: Object
__proto__: Array[0]
But the object is NOT sent in my request. If I add the object via $scope.active_filters.push(filter) it IS sent to the server but it has the index 0 and not my desired value.
How can I achieve both of my targets? A named index in my array and sending the data to the api.

I'm guessing here but your code is like this:
var assoc_array = [];
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";
JavaScript doesn't know associative arrays like for instance PHP does. JavaScript has objects, and since everything is an object (even arrays) you can get this situation.
Rather than setting the elements in the array you're assigning properties to the object. This means the magical .length property doesn't get updated because the array is still empty.
If you change you code to:
var assoc_array = {}; // <-- {} instead of []
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";
You will get an Object (instead of an Array) and you wont have a .length property.
This is how you would use an Array
var indexed_array = [];
indexed_array[0] = "bar";
indexed_array[1] = "lorem";
indexed_array.length; // 2
indexed_array[100] = "foo";
indexed_array.length; // 101 - arrays are never sparse in JS, PHP will give 3
indexed_array[2]; // undefined

Related

Check if an array or objects has a specific key

I'm trying to check if an object in an array has a key before performing a map.
My initial object array looks like:
[{label: "", value: ""}, {label: "", value: ""}]
I have a method which changes the above array so that I can post it back. This then looks like:
["STRING","STRING"]
The method I'm trying is:
var returiningUsers = [];
if (this.state.users.length > 0) {
returiningUsers = this.state.users.map(user => user.value)
console.log('has users with value');
}
return returiningUsers
The above works if there are 2 or more items in the array. When the array structure changes I get the following error: TypeError: _this.state.users.map is not a function.
I need to check if the object array key exists before doing the map function. Is this possible?
Javascript has an object property for this
myObj.hasOwnProperty('key')
I'm not sure what you mean by "changes the structure" but you can also just filter the array for objects that have the key you are looking for
if (this.state.users.length > 0) {
returiningUsers = this.state.users.filter(user => user.hasOwnProperty('value'))
}

JavaScript Two dimensional Array

I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;

Creating a 2d associative array javascript (same as a php assoc array)

I am trying to create an array in javascript which will allow me to access data like this:
var name = infArray[0]['name'];
however I cant seem to get anything to work in this way. When i passed out a assoc array from php to javascript using json_encode it structured the data in this way.
The reason why i have done this is so i can pass back the data in the same format to php to execute an update sql request.
JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.
What you want is a mix of both. Something like this:
var infArray = [{
name: 'Test',
hash: 'abc'
}, {
name: 'something',
hash: 'xyz'
}];
Then you can access it like you show:
var name = infArray[0]['name']; // 'test'
or using dot notation:
var name = infArray[0].name; // 'test'
simply var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)
JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing'] is equal to obj.something - and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length.
JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:
var myArr = { K1: {
K11: 'K11 val',
K12: 'K12 Val'
},
K2: {
K21: 'K21 Val',
K22: 'K22 Val'
}
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);

iterate through jquery data() objects and push them into another data() object (array)

How can I push an object into a jquery data() object that is an array. I want to end up with the data property numbers containing an array of objects, that I acquire by looping through some html of a particular class. I don't understand how I can push each object into the array.
My first question is, if I have some data in an object, how can I look at the whole object. It seems like it used to be that I could do
$('#div1').data('values', {'one' : 'UNO', 'two' : 'DUE'});
console.log($('#div1').data('values'))
and Chrome would give me a little expandable object to look at. Now I just see [object Object] I can still see them if I do
console.log($('#div1').data('values').one).
But that seems a little more inconvenient if I don't know exactly what's in the data() object. It would be useful for checking to see how close I am to achieving this.
Once I assign all my data to their respective objects,
$(document).ready(function(){
$('#div1').data('values', {'one' : 'UNO', 'two' : 'DUE'});
$('#div2').data('values', {'three' : 'TRE', 'four' : 'QUATTRO'});
$('#div3').data('values', {'five' : 'CINQUE', 'six' : 'SEI'});
$('#div4').data('values', {'seven' : 'SETTE', 'eight' : 'OTTO'});
});
how can I loop through these objects (all with a shared class add) and put the objects they contain in data.values into another data() object? Here I'm trying to do it on the body's data object, numbers:
`$('body').data('numbers', []);`
so that
$('body').data('numbers') =
['div1': {
'one': 'UNO',
'two': 'DUE'
},
'div2': {
'three': 'TRE',
'four': 'QUATTRO'
},
'div3': {
'five': 'CINQUE',
'six': 'SEI'
},
'div4': {
'seven': 'SETTE',
'eight': 'OTTO'
}]
my attempt has failed:
$('.add').each(function (index, element) {
$('body').data(numbers, {
element.attr('id'): element.data('values')
//could not understand how to use push here, though it seems likely that's the answer
});
jsbin
JavaScript does not have associative arrays so you have to use an Object. Then use bracket notation for the property (key) names:
var values = {};
$('.add').each(function (index, element) {
values[element.id] = $(element).data('values');
});
$('body').data('numbers', values);
jsBin
About your [object Object], you may be accidentally doing string concatenation with the object before outputting it to the console, else it is a bug in your Chrome console.
Using an array you can use .push to push items onto the end of the array:
var values = [];
$('.add').each(function (index, element) {
values.push( $(element).data('values') );
});
Bin
After having the array initialized and stored inside the element's .data(), you can later push items into it by simply grabbing a reference to the Array object and calling .push() on it:
var values = [];
$('.add').each(function (index, element) {
values.push( $(element).data('values') );
});
$('body').data('numbers', values);
$('body').data('numbers').push({'nueve': 'nine'});
//logs "nueve" too as Array/Objects/Functions are passed by reference and the
//previous command pushed an item into the Array object referenced ("stored")
//in the $('body').data('numbers')
console.log( $('body').data('numbers') );
Bin

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

Categories