Javascript: Quickly lookup value in object (like we can with properties) - javascript

I have an object that has pairs of replacement values used for simple encoding / decoding (not for security, just for a convenience; too complicated to explain it all here). It's in the form
var obj = {x: y,
x: y,
...
};
where 'x' is the value when encoded and 'y' is the decoded value.
Decoding is simple: I loop through the characters of the string, and look up the charAt(i) value in the object via brackets: obj[ str.charAt(i) ]. (I'm leaving out the check to see whether we need an uppercase or lowercase version (all key/values in the object are lowercase), but that's simple enough.)
To encode, I of course have to look for the value in the object, rather than the property. Currently, I'm looping through the properties with a for ... in ... loop and checking the values against the charAt(i) value. My current code is:
var i, j,
output = '',
str = 'Hello World!',
obj = {'s':'d',
'm':'e',
'e':'h',
'x':'l',
'z':'o',
'i':'r',
'a':'w',
'o':'!',
'-':' '};
for (i = 0; i < str.length; i++) {
for (j in obj) {
if (Object.prototype.hasOwnProperty.call(obj, j) &&
Object.prototype.propertyIsEnumerable.call(obj, j)) {
if (obj[j] === str.charAt(i)) {
output += j;
break;
} else if (obj[j].toUpperCase() === str.charAt(i)) {
output += j.toUpperCase();
break;
}
}
}
}
alert(output);
I innately feel like there should be a more efficient way of doing this. (Of course having a reversed object, {y: x}, is an option. But not a good one.) Is this the best way, or is there a better? In essence, I'd love to be able to do var prop = obj[value] just like I can do var value = obj[prop].

It's more efficient to loop just once beforehand to create a reverse map:
var str = "Hello World!",
output = '',
map = {
"s":"d", "m":"e",
"e":"h", "x":"l",
"z":"o", "i":"r",
"a":"w", "o":"!",
"-":" "
},
reverseMap = {}
for (j in map){
if (!Object.prototype.hasOwnProperty.call(map, j)) continue
reverseMap[map[j]] = j
}
output = str.replace(/./g, function(c){
return reverseMap[c] || reverseMap[c.toLowerCase()].toUpperCase()
})
console.log(output)
Instead of doing str.length * map.length, you'll do map.length + str.length operations.

A reverse encoder would make more sense, but you can write a replace function without all the hasOwnProperty etc.tests.
var str= 'Hello World!',
obj={
's':'d',
'm':'e',
'e':'h',
'x':'l',
'z':'o',
'i':'r',
'a':'w',
'o':'!',
'-':' '
}
str= str.replace(/./g, function(w){
for(var p in obj){
if(obj[p]=== w) return p;
if(obj[p]=== w.toLowerCase()) return p.toUpperCase();
};
return w;
});
returned value: (String) Emxxz-Azixso

You can create a reversed version of the mapping programmatically (instead of by hand) and use it instead.
var rev = {}
for (key in obj)
rev[obj[key]] = key

If you're looking for array keys check here.
https://raw.github.com/kvz/phpjs/master/functions/array/array_keys.js
function array_keys (input, search_value, argStrict) {
var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = '';
if (input && typeof input === 'object' && input.change_key_case) {
return input.keys(search_value, argStrict);
}
for (key in input) {
if (input.hasOwnProperty(key)) {
include = true;
if (search) {
if (strict && input[key] !== search_value) include = false;
else if (input[key] != search_value) include = false;
}
if (include) tmp_arr[tmp_arr.length] = key;
}
}
return tmp_arr;
}

Related

Compare two objects based on property names [duplicate]

I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same "type of object" as one of my model objects (Very similar to chai's instance). I just want to confirm that the two objects have the same sets of property names. I am specifically not interested in the actual values of the properties.
Let's say I have the model Person like below. I want to check that my results.data has all the same properties as the expected model does. So in this case, Person which has a firstName and lastName.
So if results.data.lastName and results.data.firstName both exist, then it should return true. If either one doesn't exist, it should return false. A bonus would be if results.data has any additional properties like results.data.surname, then it would return false because surname doesn't exist in Person.
This model
function Person(data) {
var self = this;
self.firstName = "unknown";
self.lastName = "unknown";
if (typeof data != "undefined") {
self.firstName = data.firstName;
self.lastName = data.lastName;
}
}
You can serialize simple data to check for equality:
data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)
This will give you something like
'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'
As a function...
function compare(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);
EDIT
If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section
EDIT 2
If you just want to check keys...
function compareKeys(a, b) {
var aKeys = Object.keys(a).sort();
var bKeys = Object.keys(b).sort();
return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}
should do it.
2 Here a short ES6 variadic version:
function objectsHaveSameKeys(...objects) {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
const union = new Set(allKeys);
return objects.every(object => union.size === Object.keys(object).length);
}
A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):
var x = {};
var y = {};
for (var i = 0; i < 5000000; ++i) {
x[i] = i;
y[i] = i;
}
Results:
objectsHaveSameKeys(x, y) // took 4996 milliseconds
compareKeys(x, y) // took 14880 milliseconds
hasSameProps(x,y) // after 10 minutes I stopped execution
If you want to check if both objects have the same properties name, you can do this:
function hasSameProps( obj1, obj2 ) {
return Object.keys( obj1 ).every( function( prop ) {
return obj2.hasOwnProperty( prop );
});
}
var obj1 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] },
obj2 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] };
console.log(hasSameProps(obj1, obj2));
In this way you are sure to check only iterable and accessible properties of both the objects.
EDIT - 2013.04.26:
The previous function can be rewritten in the following way:
function hasSameProps( obj1, obj2 ) {
var obj1Props = Object.keys( obj1 ),
obj2Props = Object.keys( obj2 );
if ( obj1Props.length == obj2Props.length ) {
return obj1Props.every( function( prop ) {
return obj2Props.indexOf( prop ) >= 0;
});
}
return false;
}
In this way we check that both the objects have the same number of properties (otherwise the objects haven't the same properties, and we must return a logical false) then, if the number matches, we go to check if they have the same properties.
Bonus
A possible enhancement could be to introduce also a type checking to enforce the match on every property.
If you want deep validation like #speculees, here's an answer using deep-keys (disclosure: I'm sort of a maintainer of this small package)
// obj1 should have all of obj2's properties
var deepKeys = require('deep-keys');
var _ = require('underscore');
assert(0 === _.difference(deepKeys(obj2), deepKeys(obj1)).length);
// obj1 should have exactly obj2's properties
var deepKeys = require('deep-keys');
var _ = require('lodash');
assert(0 === _.xor(deepKeys(obj2), deepKeys(obj1)).length);
or with chai:
var expect = require('chai').expect;
var deepKeys = require('deep-keys');
// obj1 should have all of obj2's properties
expect(deepKeys(obj1)).to.include.members(deepKeys(obj2));
// obj1 should have exactly obj2's properties
expect(deepKeys(obj1)).to.have.members(deepKeys(obj2));
Here's a deep-check version of the function provided above by schirrmacher.
Below is my attempt. Please note:
Solution does not check for null and is not bullet proof
I haven't performance tested it. Maybe schirrmacher or OP can do that and share for the community.
I'm not a JS expert :).
function objectsHaveSameKeys(...objects) {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), [])
const union = new Set(allKeys)
if (union.size === 0) return true
if (!objects.every((object) => union.size === Object.keys(object).length)) return false
for (let key of union.keys()) {
let res = objects.map((o) => (typeof o[key] === 'object' ? o[key] : {}))
if (!objectsHaveSameKeys(...res)) return false
}
return true
}
Update 1
A 90% improvement on the recursive deep-check version is achieved on my computer by skipping the concat() and adding the keys directly to the Set(). The same optimization to the original single level version by schirrmacher also achieves ~40% improvement.
The optimized deep-check is now very similar in performance to the optimized single level version!
function objectsHaveSameKeysOptimized(...objects) {
let union = new Set();
union = objects.reduce((keys, object) => keys.add(Object.keys(object)), union);
if (union.size === 0) return true
if (!objects.every((object) => union.size === Object.keys(object).length)) return false
for (let key of union.keys()) {
let res = objects.map((o) => (typeof o[key] === 'object' ? o[key] : {}))
if (!objectsHaveSameKeys(...res)) return false
}
return true
}
Performance Comparison
var x = {}
var y = {}
var a = {}
for (var j = 0; j < 10; ++j){
a[j] = j
}
for (var i = 0; i < 500000; ++i) {
x[i] = JSON.parse(JSON.stringify(a))
y[i] = JSON.parse(JSON.stringify(a))
}
let startTs = new Date()
let result = objectsHaveSameKeys(x, y)
let endTs = new Date()
console.log('objectsHaveSameKeys = ' + (endTs - startTs)/1000)
Results
A: Recursive/deep-check versions*
objectsHaveSameKeys = 5.185
objectsHaveSameKeysOptimized = 0.415
B: Original non-deep versions
objectsHaveSameKeysOriginalNonDeep = 0.517
objectsHaveSameKeysOriginalNonDeepOptimized = 0.342
function getObjectProperties(object, propertiesString = '') {
let auxPropertiesString = propertiesString;
for (const objectLevel of Object.keys(object).sort((a, b) => a.localeCompare(b))) {
if (typeof object[objectLevel] === 'object') {
auxPropertiesString += getObjectProperties(object[objectLevel], auxPropertiesString);
} else {
auxPropertiesString += objectLevel;
}
}
return auxPropertiesString;
}
function objectsHaveTheSameKeys(objects) {
const properties = [];
for (const object of objects) {
properties.push(getObjectProperties(object));
}
return properties.every(eachProperty => eachProperty === properties[0]);
}
It's a bit rudimentary, but should do the work in case you want to compare properties.
Legacy Browser Object Compare Function
Unlike the other solutions posted here, my Object Compare Function works in ALL BROWSERS, modern or legacy, including very old browsers, even Internet Explorer 5 (c.2000)!
Features:
Can compare an unlimited list of Objects. All must match or fails!
Ignores property order
Only compares "own" properties (i.e. non-prototype)
Matches BOTH property names and property values (key-value pairs)!
Matches functions signatures in objects!
Every object submitted is cross-compared with each other to detect missing properties in cases where one is missing but not in the other
Avoids null, undefined, NaN, Arrays, non-Objects, etc.
{} empty object detection
Works in almost ALL BROWSERS, including even Internet Explorer 5 and many other legacy browsers!
Note the function does not detect complex objects in properties, but you could rewrite the function to call them recursively.
Just call the method with as many objects as you like!
ObjectCompare(myObject1,myObject2,myObject3)
function ObjectCompare() {
try {
if (arguments && arguments.length > 0) {
var len = arguments.length;
if (len > 1) {
var array = [];
for (var i = 0; i < len; i++) {
if (
((typeof arguments[i] !== 'undefined') || (typeof arguments[i] === 'undefined' && arguments[i] !== undefined))
&& (arguments[i] !== null)
&& !(arguments[i] instanceof Array)
&& ((typeof arguments[i] === 'object') || (arguments[i] instanceof Object))
) {
array.push(arguments[i]);
}
}
if (array.length > 1) {
var a1 = array.slice();
var a2 = array.slice();
var len1 = a1.length;
var len2 = a2.length;
var noKeys = true;
var allKeysMatch = true;
for (var x = 0; x < len1; x++) {
console.log('---------- Start Object Check ---------');
//if (len2>0) {
// a2.shift();// remove next item
//}
len2 = a2.length;
if (len2 > 0 && allKeysMatch) {
for (var y = 0; y < len2; y++) {
if (x !== y) {// ignore objects checking themselves
//console.log('Object1: ' + JSON.stringify(a1[x]));
//console.log('Object2: ' + JSON.stringify(a2[y]));
console.log('Object1: ' + a1[x].toString());
console.log('Object2: ' + a2[y].toString());
var ownKeyCount1 = 0;
for (var key1 in a1[x]) {
if (a1[x].hasOwnProperty(key1)) {
// ---------- valid property to check ----------
ownKeyCount1++;
noKeys = false;
allKeysMatch = false;// prove all keys match!
var ownKeyCount2 = 0;
for (var key2 in a2[y]) {
if (a2[y].hasOwnProperty(key2) && !allKeysMatch) {
ownKeyCount2++;
if (key1 !== key1 && key2 !== key2) {// NaN check
allKeysMatch = true;// proven
break;
} else if (key1 === key2) {
if (a1[x][key1].toString() === a2[y][key2].toString()) {
allKeysMatch = true;// proven
console.log('KeyValueMatch=true : ' + key1 + ':' + a1[x][key1] + ' | ' + key2 + ':' + a2[y][key2]);
break;
}
}
}
}
if (ownKeyCount2 === 0) {// if second objects has no keys end early
console.log('-------------- End Check -------------');
return false;
}
// ---------------------------------------------
}
}
console.log('-------------- End Check -------------');
}
}
}
}
console.log('---------------------------------------');
if (noKeys || allKeysMatch) {
// If no keys in any objects, assume all objects are {} empty and so the same.
// If all keys match without errors, then all object match.
return true;
} else {
return false;
}
}
}
console.log('---------------------------------------');
return true;// one object
}
console.log('---------------------------------------');
return false;// no objects
} catch (e) {
if (typeof console !== 'undefined' && console.error) {
console.error('ERROR : Function ObjectCompare() : ' + e);
} else if (typeof console !== 'undefined' && console.warn) {
console.warn('WARNING : Function ObjectCompare() : ' + e);
} else if (typeof console !== 'undefined' && console.log) {
console.log('ERROR : Function ObjectCompare() : ' + e);
}
return false;
}
}
// TESTING...
var myObject1 = new Object({test: 1, item: 'hello', name: 'john', f: function(){var x=1;}});
var myObject2 = new Object({item: 'hello', name: 'john', test: 1, f: function(){var x=1;}});
var myObject3 = new Object({name: 'john', test: 1, item: 'hello', f: function(){var x=1;}});
// RETURNS TRUE
//console.log('DO ALL OBJECTS MATCH? ' + ObjectCompare(myObject1, myObject2, myObject3));
If you are using underscoreJs then you can simply use _.isEqual function
and it compares all keys and values at each and every level of hierarchy like below example.
var object = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};
var object1 = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};
console.log(_.isEqual(object, object1));//return true
If all the keys and values for those keys are same in both the objects then it will return true, otherwise return false.
Here is my attempt at validating JSON properties. I used #casey-foster 's approach, but added recursion for deeper validation. The third parameter in function is optional and only used for testing.
//compare json2 to json1
function isValidJson(json1, json2, showInConsole) {
if (!showInConsole)
showInConsole = false;
var aKeys = Object.keys(json1).sort();
var bKeys = Object.keys(json2).sort();
for (var i = 0; i < aKeys.length; i++) {
if (showInConsole)
console.log("---------" + JSON.stringify(aKeys[i]) + " " + JSON.stringify(bKeys[i]))
if (JSON.stringify(aKeys[i]) === JSON.stringify(bKeys[i])) {
if (typeof json1[aKeys[i]] === 'object'){ // contains another obj
if (showInConsole)
console.log("Entering " + JSON.stringify(aKeys[i]))
if (!isValidJson(json1[aKeys[i]], json2[bKeys[i]], showInConsole))
return false; // if recursive validation fails
if (showInConsole)
console.log("Leaving " + JSON.stringify(aKeys[i]))
}
} else {
console.warn("validation failed at " + aKeys[i]);
return false; // if attribute names dont mactch
}
}
return true;
}

how to cut a string in javascript

I'm receiving a String like this:
"45,21,555,64,94,796,488,\n " the \n means new line
is there a way to cut the string based on "," and getting only the "number".
I could do it C but how can I search for a character in JavaScript.
thanks for any hint
var parts = "45,21,555,64,94,796,488,\n ".split(',').filter(function(val) {
var num = parseInt(val, 10);
return !isNaN(num) && toString.call(num) === '[object Number]';
});
// parts: ["45", "21", "555", "64", "94", "796", "488"]
This is taking your String and splitting it into an Array based on a delimiter (',') and then running it through a filter function to remove anything that does not evaluate to a valid Number.
See String.prototype.split and Array.prototype.filter.
If you actually want to then convert those values to Numbers, you could chain a map call:
var parts = "45,21,555,64,94,796,488,\n ".split(',')
.filter(function(val) {
var num = parseInt(val, 10);
return !isNaN(num) && toString.call(num) === '[object Number]';
})
.map(function(val) {
return parseInt(val, 10);
});
// parts: [45, 21, 555, 64, 94, 796, 488]
Yes, like this:
var myString = "45,21,555,64,94,796,488,\n ";
var splitStrings = string.split(",");
console.log(splitStrings); //Should log an array to the console, containing only your strings e.g. [45,21,555,64,94,796,488,\n]
This returns an array of strings, split by the character you passed in. You can read more on this method here: http://www.w3schools.com/jsref/jsref_split.asp
After that, you can parse your array to remove anything you don't want like the new line character, or use a filter method to do it inline as detailed in another answer
You can use string.split(splitChar) to split. Then you can use .map or .filter to convert items to number.
var str = "45,21,555,64,94,796,488,\n ";
var arr = str.split(",");
document.write("Array: <pre>"+JSON.stringify(arr)+"</pre>");
var nums = arr.map(function(item){
return parseInt(item);
});
document.write("Numbers: <pre>"+JSON.stringify(nums)+"</pre>");
If you are wanting just the numbers as an array you could do this.
var str = "45,21,555,64,94,796,488,\n ";
var arr = str.split(","); //Make the string into an array
var len = arr.length;
for(var i=0;i<len;i++)
{
try
{
arr[i] = parseInt(arr[i]); // convert the numbers to ints
}
catch(e)
{
arr[i] = null;
}
}
As the fact that strings are just arrays, you can do it this way (a bit more comprehensive, in my opinion):
function noCommas(a)
{
var b = '';
for (var i = 0; i < a.length; i++)
{
if (a[i] != ',') //&& a[i]!= String.fromCharCode(10)) If you want no new lines too
{
b += a[i];
} else
{
//break; -> In case you only want the first value
}
}
return parseInt(b); //To return the value as an integer
}
noCommas('1234,6789'); // returns 12346789
I missunderstood the question, so here's my fixed code:
function noCommas(a)
{
var b = [];
var tempNum = '';
for (var i = 0; i < a.length; i++)
{
if (a[i] != ',' && i != a.length - 1)
{
tempNum += a[i];
} else
{
b.push(parseInt(tempNum))
tempNum = '';
}
}
return b;
}
now if you do noCommas('123,345,324234')[2] it would return 324234.

Spliting string twice with 2 separators in javascript

Let's say I need to split the string a.b.c.d#.e.f.g.h#.i.j.k.l with separator as # and then ".".
str = a.b.c.d#.e.f.g.h#.i.j.k.l
res = str.split("#")
res[0] will store a.b.c.d when I use split for the 1st time .
I need to split this again and save the data.
can anyone help ?
I think the simplest way to do it is using a regex:
var str = "a.b.c.d#.e.f.g.h#.i.j.k.l";
var res = str.split(/[.#]/);
If I may, if you have to split a string with character a then character b, the simplest in my mind would be : string.split('a').join('b').split('b')
I know this post is a bit old, but came across it, and fell like there was a better, perhaps more modern, solution. Excluding comments, this is a neat solution to this problem, and is a bit more flexible. It uses the reduce prototype, which works pretty well. This can be modified to output an object with key/value pairs as well.
const input = 'a.b.c#.e.f.g#.h.i.j'
const firstDelimiter = '#';
const secondDelimiter = '.';
// This will prevent sub arrays from containing empty values, i.e. ['','e','f','g']
const cleanInput = input.replace(/#./g, '#');
//First split by the firstDelimiter
const output = cleanInput.split(firstDelimiter).reduce( (newArr, element, i) => {
// By this point, you will have an array like ['a.b.c', 'e.f.g', 'h.i.j']
// Each element is passed into the callback, into the element variable
let subArr = element.split(secondDelimiter); // split that element by the second delimiter, created another array like ['a', 'b', 'c'], etc.
console.log(i, newArr)
// newArr is the accumulator, and will maintain it's values
newArr[i] = subArr;
return newArr;
}, []); //It's important to include the [] for the initial value of the accumulator
console.log('final:', output);
If you want to split by '#' and then for each item split by '.'
Input:'a.b.c.d#.e.f.g.h#.i.j.k'
Output:[ a b c d e f g h i j k]
var str = 'a.b.c.d#.e.f.g.h#.i.j.k.l';
var ar = [];
var sp = str.split('#');
for (var i = 0; i < sp.length; i++) {
var sub = sp[i].split('.');
for (var j = 0; j < sub.length; j++) {
ar.push(sub[j]);
}
}
alert(ar);
Here's a function I made that splits an array:
function splitArray(array, delimiter) {
let returnValue = [];
for(let i = 0; i < array.length; i++) {
array[i] = array[i].split(delimiter);
array[i].forEach(elem => {
returnValue.push(elem);
});
};
return returnValue;
};
In your case, use it like this:
str = "a.b.c.d#.e.f.g.h#.i.j.k.l";
console.log( splitArray (str.split ("#"), "." ) );
You can use the explode function similar to php
// example 1: explode(' ', 'Kevin van Zonneveld');
// returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
function explode(delimiter, string, limit) {
// discuss at: http://phpjs.org/functions/explode/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
if (arguments.length < 2 || typeof delimiter === 'undefined' || typeof string === 'undefined') return null;
if (delimiter === '' || delimiter === false || delimiter === null) return false;
if (typeof delimiter === 'function' || typeof delimiter === 'object' || typeof string === 'function' || typeof string ===
'object') {
return {
0: ''
};
}
if (delimiter === true) delimiter = '1';
// Here we go...
delimiter += '';
string += '';
var s = string.split(delimiter);
if (typeof limit === 'undefined') return s;
// Support for limit
if (limit === 0) limit = 1;
// Positive limit
if (limit > 0) {
if (limit >= s.length) return s;
return s.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
]);
}
// Negative limit
if (-limit >= s.length) return [];
s.splice(s.length + limit);
return s;
}
For more functions visit http://phpjs.org/

JS reference multi-layered dynamic object string

Suppose I have a string that references a deep Javascript object, such as:
var string = 'response.basicInfo.gender';
I want to build a function that safely checks if that object exists, by splitting the string by .s and building the object, checking each level as it goes, and then dealing with the value of the object, if it actually exists.
var parseHelper = function(response, items) {
for (item in items) {
var parts = String(item).split('.');
for (var i = 0; i < parts.length; ++i) {
// ... etc. build the string
}
}
}
parseHelper(response, {
'basicInfo.gender': function(val){
return (val == 'M') ? 'Male' : (val == 'F') ? 'Female' : val;
},
})
While the above function is incomplete, let's suppose we use it to build the string and check if each exists:
// so let's suppose we build the string:
var builtString = "response['basicInfo']";
// Now we want to check if it exists
if (response['basicInfo']) {
// And if we are fine that it exists, go on to the next item
var builtString = "response['basicInfo']['gender']";
// etc.
}
I don't have a problem building that function, I just don't know how to evaluate a string like "response['basicInfo']['gender']" and turn it into an actual reference to the object. My only guess would be eval(), but eval is evil...
Update
I know you can reference a global object by going window['blah'], but this response object I want to reference is not in the global scope, so do I use this? And even if I can do this, how do I reference it with multiple layers?
Plus 1 to Bergi, who linked to a page with six links, one of which had an answer I adapted to solve the problem:
Convert JavaScript string in dot notation into an object reference
Here's the full solution.
// We want to run a parse function to convert
// the object response.basicInfo.gender (which is 'M')
// to 'Male', etc.
// Sets the value of a string representing a deep object.
setDeep: function(root, path, value) {
var parts = path.split('.'), obj = root;
for (var i = 0; i < parts.length - 1; ++i) {
obj = obj[parts[i]] || { };
}
obj[parts[parts.length - 1]] = value;
return obj;
},
// Gets the value of a string representing a deep object.
getDeep: function(root, path) {
var parts = path.split('.'), obj = root, target;
for (var i = 0; i < parts.length; ++i) {
target = obj[parts[i]];
if (typeof target == "undefined") return void 0;
obj = target;
}
return obj;
},
// Loops through multiple string representations
// of deep objects and runs the values through
// assigned parsing functions for each of them,
// returning the root object.
parseHelper: function(obj, items) {
for (item in items) {
var val = getDeep(obj, item);
var func = items[item];
if (val !== undefined) {
val = func(val);
}
setDeep(obj, item, val);
}
return obj;
},
// response.basicInfo.gender = 'M';
// response.foo.bar = true;
response = parseHelper(response, {
'basicInfo.gender': function(val){
return (val == 'M') ? 'Male' : (val == 'F') ? 'Female' : val;
},
'foo.bar': function(val) {
return (val) ? false : true;
},
});
// response.basicInfo.gender = 'Male';
// response.foo.bar = false;

The $.param( ) inverse function in JavaScript / jQuery

Given the following form:
<form>
<input name="foo" value="bar">
<input name="hello" value="hello world">
</form>
I can use the $.param( .. ) construct to serialize the form:
$.param( $('form input') )
=> foo=bar&hello=hello+world
How can I deserialize the above String with JavaScript and get a hash back?
For example,
$.magicFunction("foo=bar&hello=hello+world")
=> {'foo' : 'bar', 'hello' : 'hello world'}
Reference: jQuery.param( obj ).
You should use jQuery BBQ's deparam function. It's well-tested and documented.
This is a slightly modified version of a function I wrote a while ago to do something similar.
var QueryStringToHash = function QueryStringToHash (query) {
var query_string = {};
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
pair[0] = decodeURIComponent(pair[0]);
pair[1] = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
};
How about this short functional approach?
function parseParams(str) {
return str.split('&').reduce(function (params, param) {
var paramSplit = param.split('=').map(function (value) {
return decodeURIComponent(value.replace(/\+/g, ' '));
});
params[paramSplit[0]] = paramSplit[1];
return params;
}, {});
}
Example:
parseParams("this=is&just=an&example") // Object {this: "is", just: "an", example: undefined}
My answer:
function(query){
var setValue = function(root, path, value){
if(path.length > 1){
var dir = path.shift();
if( typeof root[dir] == 'undefined' ){
root[dir] = path[0] == '' ? [] : {};
}
arguments.callee(root[dir], path, value);
}else{
if( root instanceof Array ){
root.push(value);
}else{
root[path] = value;
}
}
};
var nvp = query.split('&');
var data = {};
for( var i = 0 ; i < nvp.length ; i++ ){
var pair = nvp[i].split('=');
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair[1]);
var path = name.match(/(^[^\[]+)(\[.*\]$)?/);
var first = path[1];
if(path[2]){
//case of 'array[level1]' || 'array[level1][level2]'
path = path[2].match(/(?=\[(.*)\]$)/)[1].split('][')
}else{
//case of 'name'
path = [];
}
path.unshift(first);
setValue(data, path, value);
}
return data;
}
I am using David Dorward's answer, and realized that it doesn't behave like PHP or Ruby on Rails how they parse the params:
1) a variable is only an array if it ends with [], such as ?choice[]=1&choice[]=12, not when it is ?a=1&a=2
2) when mulitple params exist with the same name, the later ones replaces the earlier ones, as on PHP servers (Ruby on Rails keep the first one and ignore the later ones), such as ?a=1&b=2&a=3
So modifying David's version, I have:
function QueryStringToHash(query) {
if (query == '') return null;
var hash = {};
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var k = decodeURIComponent(pair[0]);
var v = decodeURIComponent(pair[1]);
// If it is the first entry with this name
if (typeof hash[k] === "undefined") {
if (k.substr(k.length-2) != '[]') // not end with []. cannot use negative index as IE doesn't understand it
hash[k] = v;
else
hash[k.substr(0, k.length-2)] = [v];
// If subsequent entry with this name and not array
} else if (typeof hash[k] === "string") {
hash[k] = v; // replace it
// If subsequent entry with this name and is array
} else {
hash[k.substr(0, k.length-2)].push(v);
}
}
return hash;
};
which is tested fairly thoroughly.
I know this is an old thread, but maybe there is still some relevance in it?
Inspired by Jacky Li's good solution I tried a slight variation of my own with the objective to also be able to take care of arbitrary combinations of arrays and objects as input. I looked at how PHP would have done it and tried to get something "similar" going. Here is my code:
function getargs(str){
var ret={};
function build(urlnam,urlval,obj){ // extend the return object ...
var i,k,o=obj, x, rx=/\[([^\]]*)\]/g, idx=[urlnam.replace(rx,'')];
while (x=rx.exec(urlnam)) idx.push(x[1]);
while(true){
k=idx.shift();
if(k.trim()=='') {// key is empty: autoincremented index
if (o.constructor.name=='Array') k=o.length; // for Array
else if (o===obj ) {k=null} // for first level property name
else {k=-1; // for Object
for(i in o) if (+i>k) k=+i;
k++;
}
}
if(idx.length) {
// set up an array if the next key (idx[0]) appears to be
// numeric or empty, otherwise set up an object:
if (o[k]==null || typeof o[k]!='object') o[k]=isNaN(idx[0])?{}:[];
o=o[k]; // move on to the next level
}
else { // OK, time to store the urlval in its chosen place ...
// console.log('key',k,'val',urlval);
o[k]=urlval===""?null:urlval; break; // ... and leave the while loop.
}
}
return obj;
}
// ncnvt: is a flag that governs the conversion of
// numeric strings into numbers
var ncnvt=true,i,k,p,v,argarr=[],
ar=(str||window.location.search.substring(1)).split("&"),
l=ar.length;
for (i=0;i<l;i++) {if (ar[i]==="") continue;
p=ar[i].split("=");k=decodeURIComponent(p[0]);
v=p[1];v=(v!=null)?decodeURIComponent(v.replace(/\+/g,'%20')):'';
if (ncnvt && v.trim()>"" && !isNaN(v)) v-=0;
argarr.push([k,v]); // array: key-value-pairs of all arguments
}
for (i=0,l=argarr.length;i<l;i++) build(argarr[i][0],argarr[i][1],ret);
return ret;
}
If the function is called without the str-argument it will assume window.location.search.slice(1) as input.
Some examples:
['a=1&a=2', // 1
'x[y][0][z][]=1', // 2
'hello=[%22world%22]&world=hello', // 3
'a=1&a=2&&b&c=3&d=&=e&', // 4
'fld[2][]=2&fld[][]=3&fld[3][]=4&fld[]=bb&fld[]=cc', // 5
$.param({a:[[1,2],[3,4],{aa:'one',bb:'two'},[5,6]]}), // 6
'a[]=hi&a[]=2&a[3][]=7&a[3][]=99&a[]=13',// 7
'a[x]=hi&a[]=2&a[3][]=7&a[3][]=99&a[]=13'// 8
].map(function(v){return JSON.stringify(getargs(v));}).join('\n')
results in
{"a":2} // 1
{"x":{"y":[{"z":[1]}]}} // 2
{"hello":"[\"world\"]","world":"hello"} // 3
{"a":2,"b":null,"c":3,"d":null,"null":"e"} // 4 = { a: 2, b: null, c: 3, d: null, null: "e" }
{"fld":[null,null,[2],[3,4],"bb","cc"]} // 5
{"a":[[1,2],[3,4],{"aa":"one","bb":"two"},[5,6]]} // 6
{"a":["hi",2,null,[7,99],13]} // 7
{"a":{"0":2,"3":[7,99],"4":13,"x":"hi"}} // 8
Whereas Jacky Li's solution would produce the outer container for a as a plain object
{a:{"0":["1","2"],"1":["3","4"],"2":["5","6"]}} // 6: JackyLi's output
getargs() looks at the first given index for any level to determine whether this level will be an object (non-numeric index) or an array (numeric or empty), thus resulting in the output as shown in the listing bove (no. 6).
If the current object is an array then nulls get inserted wherever necessary to represent empty positions. Arrays are always consecutively numbered and 0-based).
Note, that in the example no. 8 the "autoincrement" for empty indices still works, even though we are dealing with an object now and not an array.
As far as I have tested it, my getargs() behaves pretty much identically to Chriss Roger's great jQuery $.deparam() plugin mentioned in the accepted answer. The main difference is that getargs runs without jQuery and that it does autoincrement in objects while $.deparam() will not do that:
JSON.stringify($.deparam('a[x]=hi&a[]=2&a[3][]=7&a[3][]=99&a[]=13').a);
results in
{"3":["7","99"],"x":"hi","undefined":"13"}
In $.deparam() the index [] is interpreted as an undefined instead of an autoincremented numerical index.
Here's how you could create a new jQuery function:
jQuery.unparam = function (value) {
var
// Object that holds names => values.
params = {},
// Get query string pieces (separated by &)
pieces = value.split('&'),
// Temporary variables used in loop.
pair, i, l;
// Loop through query string pieces and assign params.
for (i = 0, l = pieces.length; i < l; i++) {
pair = pieces[i].split('=', 2);
// Repeated parameters with the same name are overwritten. Parameters
// with no value get set to boolean true.
params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
decodeURIComponent(pair[1].replace(/\+/g, ' ')) : true);
}
return params;
};
Thanks to him http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
Pretty easy :D
function params_unserialize(p){
var ret = {},
seg = p.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;}
This is really old question, but as i have coming - other people may coming to this post, and i want to a bit refresh this theme. Today no need to make custom solutions - there is URLSearchParams interface.
var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
The only one limitation i know - this feature not supported in IE / Edge.
Here's my JavaScript implementation which I use in a server-side JScript ASP Classic page (demo):
// Transforms a query string in the form x[y][0][z][]=1 into {x:{y:[{z:[1]}]}}
function parseJQueryParams(p) {
var params = {};
var pairs = p.split('&');
for (var i=0; i<pairs.length; i++) {
var pair = pairs[i].split('=');
var indices = [];
var name = decodeURIComponent(pair[0]),
value = decodeURIComponent(pair[1]);
var name = name.replace(/\[([^\]]*)\]/g,
function(k, idx) { indices.push(idx); return ""; });
indices.unshift(name);
var o = params;
for (var j=0; j<indices.length-1; j++) {
var idx = indices[j];
var nextIdx = indices[j+1];
if (!o[idx]) {
if ((nextIdx == "") || (/^[0-9]+$/.test(nextIdx)))
o[idx] = [];
else
o[idx] = {};
}
o = o[idx];
}
idx = indices[indices.length-1];
if (idx == "") {
o.push(value);
}
else {
o[idx] = value;
}
}
return params;
}
I came up with this solution, which behaves like the .Net function HttpUtility.ParseQueryString.
In the result, the query string parameters are store in properties as lists of values, so that qsObj["param"] will be the same as calling GetValues("param") in .Net.
I hope you like it. JQuery not required.
var parseQueryString = function (querystring) {
var qsObj = new Object();
if (querystring) {
var parts = querystring.replace(/\?/, "").split("&");
var up = function (k, v) {
var a = qsObj[k];
if (typeof a == "undefined") {
qsObj[k] = [v];
}
else if (a instanceof Array) {
a.push(v);
}
};
for (var i in parts) {
var part = parts[i];
var kv = part.split('=');
if (kv.length == 1) {
var v = decodeURIComponent(kv[0] || "");
up(null, v);
}
else if (kv.length > 1) {
var k = decodeURIComponent(kv[0] || "");
var v = decodeURIComponent(kv[1] || "");
up(k, v);
}
}
}
return qsObj;
};
Here is how to use it:
var qsObj = parseQueryString("a=1&a=2&&b&c=3&d=&=e&");
To preview the result in the console juste type in:
JSON.stringify(qsObj)
Output:
"{"a":["1","2"],"null":["","b",""],"c":["3"],"d":[""],"":["e"]}"
There's a beautiful one-liner over at CSS-Tricks (original source from Nicholas Ortenzio):
function getQueryParameters(str) {
return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}
The really clever part is how it uses the anonymous function's this object, adding a key/value pair for each of the queries in the string. That said, there's some room for improvement. I've modified it a bit below, with the following changes:
Added handling of empty strings and non-string input.
Handled URI-encoded strings (%40->#, etc).
Removed the default use of document.location.search when the input was empty.
Changed the name, made it more readable, added comments.
function deparam(str) {
// Uses an empty 'this' to build up the results internally
function splitQuery(query) {
query = query.split('=').map(decodeURIComponent);
this[query[0]] = query[1];
return this;
}
// Catch bad input
if (!str || !(typeof str === 'string' || str instanceof String))
return {};
// Split the string, run splitQuery on each piece, and return 'this'
var queries = str.replace(/(^\?)/,'').split('&');
return queries.map(splitQuery.bind({}))[0];
}
use this :
// convert query string to json object
var queryString = "cat=3&sort=1&page=1";
queryString
.split("&")
.forEach((item) => {
const prop = item.split("=");
filter[prop[0]] = prop[1];
});
console.log(queryString);
This is my version in Coffeescript.
Also works for url like
http://localhost:4567/index.html?hello=[%22world%22]&world=hello#/home
getQueryString: (url)->
return null if typeof url isnt 'string' or url.indexOf("http") is -1
split = url.split "?"
return null if split.length < 2
path = split[1]
hash_pos = path.indexOf "#"
path = path[0...hash_pos] if hash_pos isnt -1
data = path.split "&"
ret = {}
for d in data
[name, val] = d.split "="
name = decodeURIComponent name
val = decodeURIComponent val
try
ret[name] = JSON.parse val
catch error
ret[name] = val
return ret
Here's a simple & compact one if you only want to quickly get the parameters from a GET request:
function httpGet() {
var a={},b,i,q=location.search.replace(/^\?/,"").split(/\&/);
for(i in q) if(q[i]) {b=q[i].split("=");if(b[0]) a[b[0]]=
decodeURIComponent(b[1]).replace(/\+/g," ");} return a;
}
It converts
something?aa=1&bb=2&cc=3
into an object like
{aa:1,bb:2,cc:3}
Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests).
<button id='param'>GET</button>
<div id="show"></div>
<script>
$('#param').click(function () {
var personObj = new Object();
personObj.firstname = "vishal"
personObj.lastname = "pambhar";
document.getElementById('show').innerHTML=$.param(`personObj`));
});
</script>
output:firstname=vishal&lastname=pambhar
answers could use a bit of jQuery elegance:
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
fork at https://gist.github.com/956897
You can use the function .serializeArray() (Link) of jQuery itself. This function returns an array of key-value pair. Result example:
[
{ name: "id", value: "1" },
{ name: "version", value: "100" }
]

Categories