Skip to content

Commit a504cff

Browse files
committed
Fix _sortObj
1 parent 5cd1af9 commit a504cff

File tree

2 files changed

+33
-13
lines changed

2 files changed

+33
-13
lines changed

lib/utils/utils.js

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -80,20 +80,23 @@ function sortAttrsValues(attrs, compareAttributesAsJSON) {
8080
* @returns {Object}
8181
*/
8282
function _sortObj(obj) {
83-
var keys = _.keys(obj).sort(),
84-
sortedObj = {};
85-
86-
_.forEach(keys, function (key) {
87-
var objValue = obj[key];
88-
89-
if (_.isPlainObject(objValue)) {
90-
objValue = _sortObj(objValue);
91-
}
83+
if (!_.isObject(obj)) {
84+
return JSON.stringify(obj);
85+
}
9286

93-
sortedObj[key] = objValue;
94-
});
87+
if (_.isArray(obj)) {
88+
return '[' + _(obj).map(_sortObj).join(',') + ']';
89+
}
9590

96-
return sortedObj;
91+
return '{' +
92+
_(obj)
93+
.keys()
94+
.sort()
95+
.map(function (key) {
96+
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
97+
})
98+
.join(',') +
99+
'}';
97100
}
98101

99102
/**
@@ -132,7 +135,7 @@ function sortAttrsValues(attrs, compareAttributesAsJSON) {
132135
_.forEach(attrIndexes, function (index) {
133136
attrValue = _parseAttr(attrs[index].value, isFunction);
134137

135-
attrValue && (attrValue = JSON.stringify(_sortObj(attrValue)));
138+
attrValue = _sortObj(attrValue);
136139

137140
attrs[index].value = (isFunction && attrValue ? 'return ' : '') + attrValue;
138141
});

test/unit/utils.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,23 @@ describe('\'utils\'', function () {
6565
utils.sortAttrsValues(input, options).must.be.eql(output);
6666
});
6767

68+
it('must correctly sort attributes\' values which are objects inside arrays', function () {
69+
var options = [
70+
'a',
71+
{ name: 'onclick', isFunction: true }
72+
],
73+
input = [
74+
{ name: 'a', value: '{"a":[{"b":"b","a":"a"}]}' },
75+
{ name: 'onclick', value: 'return {"a":[{"b":"b","a":"a"}]}' }
76+
],
77+
output = [
78+
{ name: 'a', value: '{"a":[{"a":"a","b":"b"}]}' },
79+
{ name: 'onclick', value: 'return {"a":[{"a":"a","b":"b"}]}' }
80+
];
81+
82+
utils.sortAttrsValues(input, options).must.be.eql(output);
83+
});
84+
6885
it('must remove attributes\' values', function () {
6986
var input = [
7087
{ name: 'a', value: 'a' },

0 commit comments

Comments
 (0)