I currently have this code built in JS, but it's really, really ugly.
Is there any better way to approach it?
The way it works basically is pushing a string like app.chat.test to be the key, and value like teststr.
I test the lengths to see if the "parent" key is there, otherwise we build it.
function constructJson(jsonKey, jsonValue){
//REWRITE!!!!!!!!
let jsonObj = langFile;
let jsonKeyArr = jsonKey.split('.')
if (jsonKeyArr.length === 1) {
if (valToAdd === undefined) {
if (jsonObj[jsonKey] === undefined) {
jsonObj[jsonKey] = {}
}
} else {
if (jsonObj[jsonKey] === undefined) {
jsonObj[jsonKey] = valToAdd
}
}
} else if (jsonKeyArr.length === 2) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = jsonValue
}
} else if (jsonKeyArr.length === 3) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = jsonValue
}
} else if (jsonKeyArr.length === 4) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = jsonValue
}
} else if (jsonKeyArr.length === 5) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] = jsonValue
}
} else if (jsonKeyArr.length > 5) {
return console.log("Length over 5 not supported yet!")
}
return jsonObj;
}
Regards.
OF course it's possible, a simple loop will perfeclty do the job.
function constructJson(jsonKey, jsonValue){
//REWRITE!!!!!!!!
langFile = {a:{}, foo:{}};// remove this for your own code
var jsonObj = langFile;
var jsonKeyArr = jsonKey.split('.');
var currentValue = jsonObj;
for(var i = 0; i < jsonKeyArr.length;i++){
if(currentValue[jsonKeyArr[i]]===undefined){
currentValue[jsonKeyArr[i]] = {};
}
if(i < jsonKeyArr.length-1){
currentValue = currentValue[jsonKeyArr[i]];
}else{
currentValue[jsonKeyArr[i]] = jsonValue;
}
}
return jsonObj;
}
alert(JSON.stringify(constructJson("a.b.cd.ef", "toto")));
I just assigning to a temporary variable each sublevel. When i'm on the last i'm assigning the value.
Yes you can, using the javascript reduce function on the array created from the splitted string.
function namespaceCreateExceptLast(representationOfElementToCreate, baseNamespace) {
var tokens;
if (typeof representationOfElementToCreate !== 'string')
throw new Error('Expecting string as first parameter');
if (baseNamespace === undefined)
baseNamespace = window;
tokens = representationOfElementToCreate.split('.');
// Remove the last element (which will contain the value)
tokens.pop();
// Use reduce to create part by part your new object
return tokens.reduce(function (prev, property) {
if (typeof prev !== 'object') {
throw Error('One property is already defined but not an object, namespace creation has failed', property);
return undefined;
} else {
if (!prev[property])
prev[property] = {};
return prev[property];
}
}, baseNamespace);
};
Then you can have:
function constructJson(jsonKey, jsonValue){
let jsonObj = langFile;
var lastItem = namespaceCreateExceptLast(jsonKey, jsonObj);
var lastKey = jsonKey.substring(jsonKey.lastIndexOf('.') + 1);
lastItem[lastKey] = jsonValue;
}
I have added some comments and exceptions to help you understand how it's done, but it's mainly based on the reduce function which you can easily get help for (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce).
Someone mentioned I should use a true Factory pattern below so I don't have to constantly supply the typeName. How can this be accomplished within JavaScript and Angular. If it were C#, I wouldn't have a problem, but the Java reference / value types and Angular are making my brain hurt.
(function () {
'use strict';
angular
.module('blocks.object-cache');
objectCache.$inject = ['CacheFactory', '$auth'];
function objectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var service = {
setOptions : setOptions,
getCache : getCache,
clear : clear,
getAll : getAll,
getItem : getItem,
getItems : getItems,
putItem : putItem,
putItems : putItems,
getItemsByKey : getItemsByKey,
getItemByKeyFirst : getItemByKeyFirst,
getItemByKeySingle : getItemByKeySingle,
removeItemsByKey : removeItemsByKey,
removeItemByKey : removeItemByKey,
putItemsByKey : putItemsByKey,
putItemByKey : putItemByKey
};
return service;
////////////////////////////////////////////////////////////////////////////////
function setOptions (options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
_options = options;
}
function getCache(typeName) {
var cacheName = [getUserId(), normalizeTypeName(typeName || 'objects')].join('_');
var cache = CacheFactory(cacheName);
if (cache) { return cache; }
cache = CacheFactory(cacheName, _options);
return cache;
}
function clear (typeName) {
var cache = getCache(typeName);
cache.removeAll();
return (!cache.keys() || (cache.keys().length < 1));
}
function getAll (typeName) {
var cache = getCache(typeName);
var result = [];
(cache.keys() || []).forEach(function(key){
result.push(cache(key));
});
return result;
}
function getItem(typeName, id) {
if (typeof id == 'undefined' || !id.trim) { return null; }
var cache = getCache(typeName);
return cache.get(id);
}
function getItems(typeName, ids) {
var cache = getCache(typeName),
result = [],
_ids = [];
(ids || []).forEach(function(id){
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = cache.get(id);
if (item) { result.push(item); }
}
});
return result;
}
function putItem(typeName, item, id, refresh) {
if (typeof item == 'undefined') { return false; }
if (typeof id == 'undefined' || !id.trim) { return false; }
var cache = getCache(typeName);
var existing = cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { cache.remove(id); }
cache.put(item, id);
return (!!cache.get(id));
}
function putItems(typeName, items, idField, refresh) {
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[idField];
if (typeof id != 'undefined') {
var existing = cache.get(id);
if (existing && !!refresh) { cache.remove(id); }
if (!existing || !!refresh) { cache.put(item, id); }
if (!cache.get(id)) { return false; }
}
});
return true;
}
function getItemsByKey(typeName, key, value, isCaseSensitive) {
var result = [];
(getAll(typeName) || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
}
function getItemByKeyFirst(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
}
function getItemByKeySingle(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
}
function removeItemsByKey (typeName, keyField, values, isCaseSensitive) {
var cache = getCache(typeName),
keysToRemove = [];
(cache.keys() || []).forEach(function(key){
var item = cache.get[key],
itemValue = item[keyField];
if (typeof itemValue != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemValue.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemValue)) && (values[v] == itemValue)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
});
var success = true;
keysToRemove.forEach(function(key){
cache.remove(key);
if (cache.get(key)) { success = false; }
});
return success;
}
function removeItemByKey (typeName, keyField, value, isCaseSensitive) {
return removeItemsByKey(typeName, keyField, [value], isCaseSensitive);
}
function putItemsByKey(typeName, items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!removeItemsByKey(typeName, keyField, values, isCaseSensitive)) { return false; }
}
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[keyField];
if (typeof value != 'undefined') { cache.put(item, id); }
if (!cache.get(id)) { return false; }
});
return true;
}
function putItemByKey(typeName, item, keyField, refresh, isCaseSensitive) {
return putItemsByKey(typeName, [item], keyField, refresh, isCaseSensitive);
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : 'public';
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();
I'm not an Angular guru, but couldn't you just move the functions to achieve a factory-like pattern? I have not tested this, but with about two minutes of copy-n-paste...
Edit: Removed your nested iterate functions.
(function () {
'use strict';
angular
.module('blocks.object-cache')
.service('ObjectCache', ObjectCache);
ObjectCache.$inject = ['CacheFactory', '$auth'];
function ObjectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var factory = {
getCache : getCache
};
return factory;
////////////////////////////
function getCache(typeName, options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
typeName = normalizeTypeName(typeName || 'objects');
var userId = getUserId() || 'public';
var name = userId + '_' + typeName;
var service = {
type : typeName,
user : userId,
name : name,
options : options,
cache : CacheFactory(name) || CacheFactory.createCache(name, options),
clear : function () {
this.cache.removeAll();
},
getAll : function () {
var result = [];
var keys = this.cache.keys() || [];
for (var i = 0; i < keys.length; i += 1) {
result.push(this.cache(keys[i]));
}
return result;
},
getItems : function (ids) {
var result = [],
_ids = [];
for (var i = 0; i < (ids || []).length; i += 1) {
var id = ids[i];
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = this.cache.get(id);
if (item) { result.push(item); }
}
}
return result;
},
getItem : function (id) {
var items = this.getItems([id]);
return (items.length > 0) ? items[0] : null;
},
putItem : function (item, id, refresh) {
var existing = this.cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { this.cache.remove(id); }
this.cache.put(item, id);
return (!!this.cache.get(id));
},
putItems : function (items, idField, refresh) {
var success = true;
for (var i = 0; i < (items || []).length; i += 1) {
var item = items[i];
var id = item[idField];
if (typeof id != 'undefined') {
if (this.putItem(item, id, refresh)) { success = false; }
}
}
return success;
},
getItemsByKey : function (key, value, isCaseSensitive) {
var result = [];
(this.getAll() || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
},
getItemByKeyFirst : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
},
getItemByKeySingle : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
},
removeItemsByKey : function (keyField, values, isCaseSensitive) {
var keysToRemove = [],
keys = this.cache.keys() || [];
for (var k = 0; k < keys.length; k += 1) {
var key = keys[k];
var item = this.cache.get(key);
var itemVal = item[keyField];
if (typeof itemVal != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemVal == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemVal.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemVal)) && (values[v] == itemVal)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
}
var success = true;
for (var r = 0; r < keysToRemove.length; r += 1) {
this.cache.remove(keysToRemove[r]);
if (this.cache.get(keysToRemove[r])) { success = false; }
}
return success;
},
removeItemByKey : function (keyField, value, isCaseSensitive) {
return this.removeItemsByKey(keyField, [value], isCaseSensitive);
},
putItemsByKey : function(items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!this.removeItemsByKey(keyField, values, isCaseSensitive)) { return false; }
}
for (var i = 0; i < (items || []).length; i += 1) {
var id = items[i][keyField];
if (typeof id != 'undefined') {
this.cache.put(items[i], id);
if (!this.cache.get(id)) { return false; }
}
}
return true;
},
putItemByKey : function (item, keyField, refresh, isCaseSensitive) {
return this.putItemsByKey([item], keyField, refresh, isCaseSensitive);
}
};
return service;
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : null;
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();
Can i optimize my code bit more to reduce number of line?
I am checking/passing individual array elements? Can i make it re-write in a generic way?
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
if (_isValueNan($$scope.studentReport.Students[i].Age))
$$scope.studentReport.Students[i].Age = null;
if (_isValueNan($$scope.studentReport.Students[i].Number))
$$scope.studentReport.Students[i].Number = null;
if (_isValueNan($$scope.studentReport.Students[i].Height))
$$scope.studentReport.Students[i].Height = null;
}
var _isValueNan = function (item) {
var result = false;
if (typeof item == 'number' && isNaN(item))
result = true;
return result;
}
With ref to Stumblor's answer:
for (var i = 0; i < $scope.studentReport.Students.length; i++) {
_checkValueNan($$scope.studentReport.Students[i], ["Age", "Number", "Height"]);
}
var _checkValueNan = function (item, values) {
values.forEach(function (val) {
if (typeof item[val] === 'number' && isNaN(item[val])) item[val] = null;
});
}
You can nullify the property internally in the function, and also pass the item and property value in independently. For example:
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
_checkValueNan($$scope.studentReport.Students[i], "Age");
_checkValueNan($$scope.studentReport.Students[i], "Number");
_checkValueNan($$scope.studentReport.Students[i], "Height");
}
var _checkValueNan = function (item, valueName) {
if (typeof item[valueName] == 'number' && isNaN(item[valueName]))
item[valueName] = null;
}
EDIT:
Leading on from Vicky Gonsalves answer, you could additionally check ANY of the properties of the object, which might be a more scalable solution.
var _checkAllValueNan = function (item) {
for(var key in item) { // iterates all item properties
if (!item.hasOwnProperty(key)) continue; // ensures not prop of prototype
if (typeof item[key] == 'number' && isNaN(item[key])) item[key] = null;
}
}
for (var i = 0; i < $scope.studentReport.Students.length; i++)
{
_checkAllValueNan($scope.studentReport.Students[i]);
}
The hierarchy can be very deep, So how to check if the a property exists somewhere within the root object ? If not then create it.
I have the following html
<div id="container">
<div id="level-1">
<input id="value-1" group="a.b" name="c" value="some-value-1">
</div>
</div>
Now i would like to put the value of this input into a javascript object based on the parent attribute.
Desired output is
{
"a" : {
"b" : {
"c" : "some-value-1"
}
}
}
My Effort :
function traverse(id, obj) {
var methodName = "traverse";
var elementToTraverse = document.getElementById(id);
var currentElementLength = elementToTraverse.childNodes.length;
if (currentElementLength > 0) {
var children = getChildNodes(elementToTraverse);
for (var ch in children) {
var currentChild = children[ch];
//ignore the text nodes
if (currentChild.nodeType == 3) {
continue;
}
if (currentChild.nodeType == 1 && currentChild.childNodes.length > 0 && currentChild.id != "") {
//call without the object argument as it has already been constructed.
traverse(currentChild.id, obj);
}
else if (currentChild.nodeType == 1 && currentChild.id != "" && currentChild.getAttribute('name') != null) {
if (DEBUG) {
logOnConsole(methodName, currentChild.getAttribute('name') + "--" + currentChild.id, logLevel.INFO);
}
var group = currentChild.getAttribute('group') || null;
var name = currentChild.getAttribute('name');
var value = getValue(currentChild);
if (value == "" || value == undefined) {
if(group){
if(isNull(obj[group])){
obj[group] = new Object();
}
obj[group][name] = "";
}
else{
obj[name] = "";
}
}
else if(group){
if(isNull(obj[group])){
obj[group] = new Object();
}
obj[group][name] = value;
}
else {
obj[name] = value;
}
}
else {
if (DEBUG) {
logOnConsole(methodName, "Element not useful. \n" + currentChild.nodeName, logLevel.INFO);
}
}
}
}
return obj;
}
I call it via traverse('container-id', new Object()) but this will work for a single value in the group rather than a nested structure.
Try this
function isExist(obj, path) {
patharray = path.split(".");
for(var i=0;i < patharray.length; i++) {
obj = obj[patharray[i]];
if(obj === undefined) return false
}
return true;
}
document.body.innerHTML = isExist({subobject:{subsubobject:{test: 34}}}, 'subobject.subsubobject');
I always need to deal with multi-level js objects where existence of properties are not certain:
try { value1 = obj.a.b.c; } catch(e) { value1 = 1; }
try { value2 = obj.d.e.f; } catch(e) { value2 = 2; }
......
Is there an easier way or a generic function (e.g. ifnull(obj.d.e.f, 2) ) that does not require a lot of try catches?
var value1 = (obj.a && obj.a.b && obj.a.b.c) || 1;
http://jsfiddle.net/DerekL/UfJEQ/
Or use this:
function ifNull(obj, key, defVal){
var keys = key.split("."), value;
for(var i = 0; i < keys.length; i++){
if(typeof obj[keys[i]] !== "undefined"){
value = obj = obj[keys[i]];
}else{
return defVal;
}
}
return value;
}
var value1 = ifNull(obj, "a.b.c", 1);
You could always create a helper function.
function isUndefined(root, path, defaultVal) {
var parts = path.split('.'),
i = 0,
len = parts.length,
o = root || {}, v;
while ((typeof (v = o[parts[i]]) === 'object', o = v) && ++i < len);
return (typeof v === 'undefined' || i !== len)? defaultVal: v;
}
var obj = {a: { b: { test: 'test' }}}, v;
v = isUndefined(obj, 'a.b.test', 1); //test
v = isUndefined(obj, 'a.test', 1); //1
Using lodash you can do this easily**(node exists and empty check for that node)**..
var lodash = require('lodash-contrib');
function invalidateRequest(obj, param) {
var valid = true;
param.forEach(function(val) {
if(!lodash.hasPath(obj, val)) {
valid = false;
} else {
if(lodash.getPath(obj, val) == null || lodash.getPath(obj, val) == undefined || lodash.getPath(obj, val) == '') {
valid = false;
}
}
});
return valid;
}
Usage:
leaveDetails = {
"startDay": 1414998000000,
"endDay": 1415084400000,
"test": { "test1" : 1234 }
};
var validate;
validate = invalidateRequest(leaveDetails, ['startDay', 'endDay', 'test.test1']);
it will return boolean.