After lots of tries and searching I decide to ask because I am stuck.I have a txt file like this:
CITYS
CITYS.AREAS
CITYS.AREAS.STREETS
CITYS.AREAS.STREETS.HOUSES
CITYS.AREAS.STREETS.HOUSES.ROOMS
CITYS.AREAS.STREETS.HOUSES.ROOMS.KITCHEN
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TV
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.VASE
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.ASTREY
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.SHAMPOO
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.CONTITIONER
CITYS.AREAS.STREETS.HOUSES.GARDEN
CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL
CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL.WATER
CITYS.AREAS.STREETS.HOUSES.GARDEN.TREE.....
CITYS.AREAS.STREETS.CARS
CITYS.AREAS.STREETS.CARS.BRAND...
CITYS.AREAS.STREETS.CARS.BRAND.LOGO.....
CITYS.AREAS.STREETS.CARS.COLOR..
CITYS.AREAS.STREETS.CARS.TYPE..
And I want to convert it into a nested object like this
CITYS:{
AREAS:{
STREETS:{
HOUSES:{
ROOMS: {
LIVINGROOMS: {TV,TABLE:{VASE,ASTREY}},
BATHROOMS: {BATHTUBE:{SHAMPOO,CONTITIONER},MIRROR},
...
},
GARDEN:{
......
},
},
CARS:{
BRAND:{LOGO},
COLOR:{},
TYPE:{},
......
},
},
}
}
I am tring to do somthing like that (IN ARRAY)
for(var line = 0; line < lines.length; line++){
var n = lines[line];
var ninpieces = n.split(".");
var name=ninpieces[ninpieces.length-1];
var nametostore=ninpieces[ninpieces.length-2] ;
CreateObject(name,nametostore);
};
CreateObject=function(name,nametostore){
this.a= name;
this.b= nametostore;
newpar=this['b'];
newchild=this['a'];
this[newchild]=new Array();
if (typeof this[newpar] != "object") {
this[newpar]=new Array();
}
this[newchild].push(name);
this[newpar].push(this[newchild])
stractureobj.push(this[newpar])
}
Is a combination of things that I found here in stackoverflow but it's not working.
You can use the following code. This "algorithm" temporarily stores also properties by their fully dotted names, as synonyms for the corresponding nested objects. This way it can quickly retrieve where to inject the next line's object.
Note that the algorithm performs fastest if the input is sorted. This you can do with lines.sort() if necessary.
function addNestedObject(obj, lines) {
var map = { '': obj }; // Set starting point for empty path
function addLine(line) {
var name = line.split(".").pop();
var path = line.substr(0, line.length-name.length-1);
if (!map[path]) addLine(path); // recurse to create parent
if (!map[line]) map[line] = map[path][name] = {}; // set name & line synonym
}
// Process each line with above private function.
for (var line of lines.slice().sort()) addLine(line);
return obj; // Might be useful to have as return value as well
};
// Sample input
var lines = [
'CITYS.AREAS',
'CITYS.AREAS.STREETS',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TV',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.VASE',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.ASTREY',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.SHAMPOO',
'CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.CONTITIONER',
'CITYS.AREAS.STREETS.HOUSES.GARDEN',
'CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL',
'CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL.WATER',
'CITYS',
];
var stractureobj = { 'otherProperty': 42 };
// Convert lines to nested object and add to stractureobj
addNestedObject(stractureobj, lines);
// Output in snippet
document.querySelector('pre').textContent=JSON.stringify(stractureobj, null, 4);
<pre></pre>
The above uses an object stractureobj, with already its own properties, to which the nested structure must be added.
If you are only interested to have an object with just the nested structure, and nothing else, you could call it with the empty object and assign the return value:
var stractureobj = addNestedObject({}, lines);
Which comes down to the same as this:
var stractureobj = {};
addNestedObject(stractureobj, lines);
You can use String.prototype.split() with RegExp /\n/ as parameter to split text file at new line characters, Array.prototype.filter() with parameter Boolean to remove empty items from array; set stractureobj to an empty object; use single for loop, Array.prototype.reduce() to set properties of stractureobj
for (var line = 0
, stractureobj = {}
, lines = textFileContents.split(/\n/).filter(Boolean)
; line < lines.length
; line++) {
var n = lines[line];
if (line === 0) {
stractureobj[lines[line]] = {}
} else {
var ninpieces = n.split(/\./).filter(Boolean);
ninpieces.reduce(function(obj, prop, index) {
var curr = ninpieces[index + 1];
if (!obj[prop] && !!curr) {
obj[prop] = {
[curr]: {}
};
} else {
if (obj[prop] && curr
&& !obj[prop][curr]) {
obj[prop][curr] = {}
}
}
return obj[prop]
}, stractureobj)
}
};
for (var line = 0
, stractureobj = {}
, lines = document.querySelector("pre")
.textContent.split(/\n/).filter(Boolean)
; line < lines.length
; line++) {
var n = lines[line];
if (line === 0) {
stractureobj[lines[line]] = {}
} else {
var ninpieces = n.split(/\./).filter(Boolean);
ninpieces.reduce(function(obj, prop, index) {
var curr = ninpieces[index + 1];
if (!obj[prop] && !!curr) {
obj[prop] = {
[curr]: {}
};
} else {
if (obj[prop] && curr && !obj[prop][curr]) {
obj[prop][curr] = {}
}
}
return obj[prop]
}, stractureobj)
}
};
document.querySelectorAll("pre")[1].textContent = JSON.stringify(stractureobj, null, 2)
pre:nth-of-type(1) {
display: none;
}
<pre>CITYS
CITYS.AREAS
CITYS.AREAS.STREETS
CITYS.AREAS.STREETS.HOUSES
CITYS.AREAS.STREETS.HOUSES.ROOMS
CITYS.AREAS.STREETS.HOUSES.ROOMS.KITCHEN
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TV
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.VASE
CITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.ASTREY
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.SHAMPOO
CITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.CONTITIONER
CITYS.AREAS.STREETS.HOUSES.GARDEN
CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL
CITYS.AREAS.STREETS.HOUSES.GARDEN.POOL.WATER
CITYS.AREAS.STREETS.HOUSES.GARDEN.TREE
CITYS.AREAS.STREETS.CARS
CITYS.AREAS.STREETS.CARS.BRAND
CITYS.AREAS.STREETS.CARS.BRAND.LOGO
CITYS.AREAS.STREETS.CARS.COLOR
CITYS.AREAS.STREETS.CARS.TYPE
</pre>
<pre></pre>
I guess in JS it's essential to have "dynamic" access to nested values both to get or set them. I think this is a missing functionality. So i decided to develop two reusable Object methods. They are Object.prototype.getNestedValue() and Object.prototype.setNestedValue() They are very handy tools for these use cases and just turn your job nothing more than a very simple task. OK let's get into them to see what they are.
setNestedValue() takes a number of arguments. All arguments except the last one are used as object properties if it's a "string" type or array index if it's a "number" type. The last argument is the value of the last object property or array index at the very last in line. Accordingly.
var o = {};
o.setNestedValue("a",3,"b","value");
or
var o = {};
o.setNestedValue(...["a",3,"b"],"value");
are typical use cases. Lets see a simple example.
Object.prototype.setNestedValue = function(...a) {
a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
: (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
this[a[0]].setNestedValue(...a.slice(1)))
: this[a[0]] = a[1];
return this;
};
var o = {};
o.setNestedValue("a",3,"x","value");
o.setNestedValue("a",2,"y","value");
o.setNestedValue("a",1,"z","value");
o.setNestedValue("a",0,"w","value");
console.log(JSON.stringify(o,null,2));
OK now it's the time for your solution;
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
Object.prototype.setNestedValue = function(...a) {
a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
: (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
this[a[0]].setNestedValue(...a.slice(1)))
: this[a[0]] = a[1];
return this;
};
var data = "CITYS\nCITYS.AREAS\nCITYS.AREAS.STREETS\nCITYS.AREAS.STREETS.HOUSES\nCITYS.AREAS.STREETS.HOUSES.ROOMS\nCITYS.AREAS.STREETS.HOUSES.ROOMS.KITCHEN\nCITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS\nCITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TV\nCITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE\nCITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.VASE\nCITYS.AREAS.STREETS.HOUSES.ROOMS.LIVINGROOMS.TABLE.ASTREY\nCITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS\nCITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE\nCITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.SHAMPOO\nCITYS.AREAS.STREETS.HOUSES.ROOMS.BATHROOMS.BATHTUBE.CONTITIONER\nCITYS.AREAS.STREETS.HOUSES.GARDEN\nCITYS.AREAS.STREETS.HOUSES.GARDEN.POOL\nCITYS.AREAS.STREETS.HOUSES.GARDEN.POOL.WATER\nCITYS.AREAS.STREETS.HOUSES.GARDEN.TREE\nCITYS.AREAS.STREETS.CARS\nCITYS.AREAS.STREETS.CARS.BRAND\nCITYS.AREAS.STREETS.CARS.BRAND.LOGO\nCITYS.AREAS.STREETS.CARS.COLOR\nCITYS.AREAS.STREETS.CARS.TYPE",
datarr = data.split("\n").map(e => e.split(".")), // get your list in an array
o = {};
datarr.forEach(a => o.setNestedValue(...a,""));
console.log(JSON.stringify(o,null,2));
Allright.. that's it... It's so simple.
Related
There is a question about sorting and adding an object, more precisely for example:
I have a string a1/b1/c1/d1 that
spl = "a1/b1/c1/d1".split ("/") and at the output I get an array of 4 elements.
I have an object - obj, I need to cycle through the spl array and each new turn I added values, right now I'll tell you
for(var i = 0; i < spl.length(); i++){
// and here's the code I don't know how to write
}
/* there must be something like this
//if obj[spl[0]] is existing then do
i = 0: obj[spl[0]] = {};
//if obj[spl[0]][spl[1]] is existing then do
i = 1: obj[spl[0]][spl[1]] = {};
//if obj[spl[0]][spl[1]][spl[2]] is existing then do
i = 2: obj[spl[0]][spl[1]][spl[2]] = {};
//and if the last element of the massiv is not existing then do
i = 3: obj[spl[0]][spl[1]][spl[2]][spl[3]] = {};
/if the last element of the massiv is existing then do nothing
the end of the cycle*/
that is, each scroll is added as long as i is less than the length of the array
it should work like this
obj {
a1:{
b1:{
c1:{
d1:{}
}
}
}
};
For example, if I have 2 elements in spl, the loop will add only 2 times as in the example, if 5, then 5
Not sure if I understand the question correctly, is this what you want to achieve?
let obj = {}
let path = 'a1/a2/a3'.split('/')
let current = obj
for (let prop of path) {
current[prop] = current[prop] || {}
current = current[prop]
}
console.log(obj)
let spl = "a1/b1/c1/d1".split ("/")
let obj = {}
let temp = obj
for(let i = 0; i < spl.length; i++) {
temp[spl[i]] = {}
temp = temp[spl[i]]
}
console.log(obj)
For every iteration, temp is updated.
So, initially temp is obj but in the first iteration temp["a1"] is set to an empty object and then temp's value is updated to temp["a1"]. At this point again temp is an empty object. And for the next iteration temp["b1"] set to an empty object and the loop continues.
Since objects are passed by reference, obj is being updated throughout the process which results in the required output format.
I'm not sure why you really need to check if nested property already exists, because it certainly won't be in an empty object, so I avoided this check.
const buildObjectFromPath = splitter => path => {
path = path.split(splitter)
const obj = {}
let current = obj
for (const prop of path) {
current = current[prop] = {}
}
return obj
}
const path = 'a1/b1/c1/d1'
console.log(buildObjectFromPath('/')(path))
:)
Use reduceRight will simplify as one line
const obj = "a1/a2/a3/a4"
.split("/")
.reduceRight((acc, curr) => ({ [curr]: acc }), {});
console.log(obj);
I have found the answer. You can change path and comment var obj = {}. First, if you want to create a1 in obj you have to change path to a1. The script will check the path and create it in obj. After that. You can add /b1 to a1 to create b1 in a1 and etc.
If you make a mistake in the path (var obj = {} and var path = 'a1/b1/c1'.split("/");) the program will output the error. console.log("Wrong path_2"); - (here) b1 - is not found. console.log("Wrong path_1"); - (here) a1 - is not found.
In this script I have var obj = {} and path = ["a1","b1"]. obj doesn't have a1 so console will output 'Wrong path_1' and our obj
var path = 'a1/b1'.split("/");
var obj = {};
var addition = "";
var elem_name = "";
for(elem of path){
if(obj[elem] === undefined && path.length === 1){
obj[elem] = {};
console.log(`${elem} have been created`);
}else if(obj[elem] !== undefined && path.length > 1){
obj = obj;
addition = obj[elem];
elem_name = elem;
}else if(addition[elem] === undefined && path.length > 1 && addition !== ""){
if(elem === path[path.length-1]){
addition[elem] = {};
console.log(`${elem} have been created in ${elem_name}`);
break;
}else if(elem !== path[path.length-1]){
console.log("Wrong path_2");
break;
}
}else if(addition[elem] !== undefined && path.length >1){
obj = obj;
addition = addition[elem];
elem_name = elem;
console.log(`${elem} was created earlier`);
}else if(obj[elem] === undefined && path.length > 1){
console.log(`Wrong path_1`);
break;
}else if(obj[elem] !== undefined && path.length === 1){
console.log(`${elem} was created earlier`);
break;
}
}
console.log(obj);
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;
}
I'm trying to create tree from a list . My data is like ;
A-->B-->C-->D-->E..
A-->B-->C-->D-->F..
A-->F-->C-->D-->E..
.
.
.
I have all possible data path in array.I want to show this like
A
-B
-C
-D
-E
-F
-F
-C
-D
-E
How can i create and check with javascript ? I need createTreeFunction :)
function parseData(data)
{
$.each(data, function (i, p) {
var arr = p.split("--->");
createTreeFunction(p);
});
};
function parseData(data)
{
$.each(data, function (i, p) {
var arr = p.split("--->");
createTreeFunction(p);
});
};
Basically you can use at least two different structures for the children for building a tree, one with an array (Solution A) or with an object (Solution B).
The advantage of an array over an object is the direct iteration over the children. With an object, you need to get the keys first and then is an iteration possible.
Otherwise if you know one child, then the access over the key is faster. This is also true for inserting new nodes to the tree.
With a children array you need a function getChild for testing if a child is present.
A note, the supplied data does not keep the identifier unique.
Solution A with arrays for children:
function Node(id) {
this.id = id;
this.children = []; // array
}
Node.prototype.getChild = function (id) {
var node;
this.children.some(function (n) {
if (n.id === id) {
node = n;
return true;
}
});
return node;
};
var path = ['A-->B-->C-->D-->E', 'A-->B-->C-->D-->F', 'A-->F-->C-->D-->E'],
tree = new Node('root');
path.forEach(function (a) {
var parts = a.split('-->');
parts.reduce(function (r, b) {
var node = r.getChild(b);
if (!node) {
node = new Node(b);
r.children.push(node);
}
return node;
}, tree);
});
document.getElementById('out').innerHTML = JSON.stringify(tree, 0, 4);
<pre id="out"></pre>
Solution B with objects for children:
function Node(id) {
this.id = id;
this.children = {}; // object
}
var path = ['A-->B-->C-->D-->E', 'A-->B-->C-->D-->F', 'A-->F-->C-->D-->E'],
tree = new Node('root');
path.forEach(function (a) {
var parts = a.split('-->');
parts.reduce(function (r, b) {
if (!r.children[b]) {
r.children[b] = new Node(b);
}
return r.children[b];
}, tree);
});
document.getElementById('out').innerHTML = JSON.stringify(tree, 0, 4);
<pre id="out"></pre>
Both proposals uses Array#forEach and Array#reduce for iterating the given strings and for returning the reference to the actual id. If an id is not found, a new instance of node is taken and added to the array or object. The reference is returned for the next id check.
For this use cases i had invented very useful two Object methods; namely Object.prototype.getNestedValue() and Object.prototype.setNestedValue(). By utilizing these methods this job is nothing more than a single liner JS code. See below...
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
Object.prototype.setNestedValue = function(...a) {
return a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
: (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
this[a[0]].setNestedValue(...a.slice(1)))
: this[a[0]] = a[1];
};
var data = "A-->B-->C-->D-->E\nA-->B-->C-->D-->F\nA-->F-->C-->D-->E",
datarr = data.split("\n").map(e => e.split("-->")), // get your list in an array
o = {};
datarr.forEach(a => !o.getNestedValue(...a) && o.setNestedValue(...a,null));
console.log(JSON.stringify(o,null,2));
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;
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" }
]