Converting javascript dictionary to array/object to be passed in jquery.params - javascript

I have a javascript variable which is a dictionary of key-values pairs of querystring. I need to again convert this dictionary into a query string. I am using jquery.param functin but it takes either an array or an object. How can I convert my dictinoary variable to array/object which jquery.params can accept.
Tried using serializeArray but it does not work.

The jQuery.param method can take an array i in this form:
[{ name: 'asdf', value: '42' },{ name: 'qwerty', value: '1337' }]
If your dictionary have other property names, you can use the jQuery.map method to convert it. Example:
arr = $.map(arr, function(e){
return { name: e.key, value: e.val };
});

If I understand your question right (some code samples would help!) by "dictionary" you mean a construction like:
var dict = { key1: value1, key2: value2 … }
or:
var dict = {};
dict[key1] = value1;
dict[key2] = value2;
or possibly:
var dict = {};
dict.key1 = value1;
dict.key2 = value2;
If so, you should know that all of these are doing the same thing, i.e. setting properties on JavaScript objects, and should be serialised correctly by jQuery.param. Succinctly, JavaScript objects ≈ dictionaries.

use Object.values() :
var arr = Object.values(some_dict)

Related

how to add many values to one key in javascript object

I have an object var obj = {key1: "value1", key2: "value2"}; I want to add multiple values or array of values to key1 or key2 e.g
var obj = {key1: "arrayOfValues", key2: "value2"}; is it possible? basically I want to send it to php for process.
You can just define an array for the property:
var obj = {key1: ["val1", "val2", "val3"], key2: "value2"};
Or, assign it after the fact:
var obj = {key2: "value2"};
obj.key1 = ["val1", "val2", "val3"];
You can make objects in two ways.
Dot notation
Bracket notation
Also you can be define values in array with/without initial size.
For scenario one you can do the following in worst case scenario:
var obj = {}
obj.key1 = new Array();
obj.key2 = new Array();
// some codes related to your program
obj.key1.push(value1);
// codes ....
obj.key1.push(value);
// ... same for the rest of values that you want to add to key1 and other key-values
If you want to repeat the above codes in bracket notation, it will be like this
var obj = {}
obj['key1'] = new Array();
obj['key2'] = new Array();
// some codes related to your program
obj['key1'].push(value1);
// codes ....
obj['key1'].push(value);
// ... same for the rest of values that you want to add to key1 and other key-values
With bracket notation, you can use characters e.g 1,3,%, etc. that can't be used with dot notation.
I came across same scenario and after scanning through many resources I found very elegant solution. Using Bracket Notation one can add multiple values to same key
let obj = {}
const demo = (str, objToAdd) => {
if(!obj[str]){
obj[str] = {}
}
const key = Object.keys(objToAdd)[0]
obj[str][key] = Object.values(objToAdd)[0]
}
Here important line is obj[str][key] = Object.values(objToAdd)[0]. This line will help you create object inside same key. obj[str][key] will create object inside object.
to add values call function as below
demo('first', {content: 'content1' } )
demo('first', {content2: 'content3' } )
obj
first: {content: "content1", content2: "content3"}
Hopefully this will help someone.

Use pop() with JavaScript Associative Arrays

How can I do something like the following in JS? I would like to imitate .pop() on an object rather than an array.
var deck = {
'cardK' :'13',
'cardQ' :'12',
'cardAJ':'11'
};
var val = deck.pop();
console.log("Key" + val.key );
console.log("Value" + val.val );
It seems like it's not possible.
.pop is only available on an array. In JavaScript, objects (which are essentially associative arrays) are not ordered like an array, so there is no .pop method.
You could use an array:
var deck = [
{ key: 'cardK', val: 13 },
{ key: 'cardQ', val: 12 },
{ key: 'cardAJ', val: 11 },
];
var val = deck.pop();
console.log('key: ' + val.key);
console.log('aa: ' + val.val);
As suggested by other answers, the best solution here might be to use an array of objects. However you could also create your own pop function that removes a key from an object, for example:
function pop(obj) {
var key = Object.keys(obj).pop();
var result = {key: key, val: obj[key]};
delete obj[key];
return result;
}
var val = pop(deck);
You could add a similar pop function to Object.prototype so that you could do deck.pop(), but I would strongly recommend against that type of design.
You are right, it's not possible. See objects as maps or hash tables, rather than "associative arrays". The properties don't have an order and thus a method such as .pop would not make sense (unless of course it would remove a random property, like Python's dictionaries).
If you want to to use .pop and val.key and val.val, you have to create an array of objects instead:
var deck = [
{key: 'cardK', val: '13'},
{key: 'cardQ', val: '12'},
{key: 'cardAJ', val: '11'}
];
As I'm sure you know, .pop is a prototypal Array method, so you can't use it with Javascript objects.
Calling .pop on an array will remove the last element from the array. However, there isn't a "last" key-value pair with objects, as their order is not ever guaranteed. Despite this, if you don't care about order, you could implement a .pop-like function for use with objects, though, again, it wouldn't remove and return the final key-value pair.
Something like this should do the trick:
function pop(obj) {
for (var key in obj) {
var val = obj[key];
delete obj[key];
return {
'key' : key,
'val' : val,
};
};
};
Combined with your code:
var val = pop(deck);
console.log('key: ' + val.key);
console.log('aa: ' + val.val);
When working with this structure, which can be thought of as an associative array, you need to use different techniques. Things like pop(), slice() and even .length will not work as they do with numeric keyed arrays.
I use string keyed object arrays when searching for the key/value pair needs to happen fast.
Here's a jsPef I just created which shows the benefit of your array structure:
http://jsperf.com/bmcgin-object-array-tests (keep in mind the performance goes way up as the array gets bigger)
Also keep in mind the value can be a number, a string, an array, a function, an object ect...

Converting array in object to string

I want the array in an object to be a string. can someone pl help? So im passing an array into an object and Im expecting var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort'; how can this be attained ?
it("should serialize an object with another object/array in it", function() {
var object2 = {
'name': 'bob',
'age': 24,
'kids': [ 'billy', 'bart', 'bort' ]
};
var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort';
expect(NUUI.Utils.serializeForQueryString(object2))
.toEqual(expectedResultForObject2);
});
You need serialized result from an object. This can be achieved with jQuery.param()
uri = $.param(object2);
More information on this, you can find in jQuery Manual.
Alternatively, you can make an array object a string simply with .join() method of the array
string = array.join('');
This question is heavily answered in SO
jQuery serialize an object?

Confuse about array and object in node.js

I have a array for store object, which have an object in it already:
var obj = [{
name: 'json',
lang: 'en'
}];
console,.log(obj) //the result is OK;
then I want push another object into it, just like:
var newObj = {
name: 'lee',
lang: 'zh'
}
obj.push(newObj)
but after this I print the obj array,console.log(obj), the result is 2 !!
Why this happen? How can I solve this problem?To store object in array correctly
Make sure you didn't do obj = obj.push(newObj);, because .push method returns the number of elements after push; instead, the line should simply read obj.push(newObj).

Delete entries from an associative array (JavaScript)

I currently have a problem in deleting entries from an associative array in JS.
I tried this:
myArray['key'] = value;
myArray['key1'] = value1;
...
delete myArray['key'];
But I get following results in my application:
[ undefined, { key1: 'value1', key2: 'value2' }, undefined,
{ key1: 'value1', key2: 'value2' }, undefined, undefined ]
How can I delete the whole entry, key and value? I found the method splice() but I think it uses a different index. I wasn't able to delete the entries I want by passing the key to splice().
It seems you are mixing arrays and objects. Associative arrays should be realized with objects:
myArray = {};
myArray['key'] = value;
myArray['key1'] = value1;
It is a bit confusing though because in your output, the objects don't have key anymore (so it worked), but the array containing those objects as undefined values. I cannot see how
delete myArray['key']; is related to your output and which variable now contains which value (please clarify).
But it looks like you did something like:
var container = new Array(6);
container[1] = myArray;
container[3] = myArray;
This will initialize the array with 6 undefined values (sort of) and then set the second and forth value to something else.
If you want to use that "array" as associative array, you should declare it as object too:
var container = {};
Please post more code if you need a better answer.
Update: Yes, you should declare displayedWidgets as object:
var widgets = {
displayedWidgets: {},
clear: function() {
this.displayedWidgets = {};
},
add: function(widget) {
this.displayedWidgets[widget.id] = widget;
},
addArray: function(newWidgets) {
// note that `each` is only available in newer browsers,
// just loop over the array
for(var i = newWidgets.length; i--; ) {
this.add(newWidgets[i]);
}
},
remove: function(widgetId) {
if (widgetId in this.displayedWidgets) {
delete this.displayedWidgets[widgetId];
}
}
};

Categories

Resources