I want to create a dictionary in JavaScript like the following:
myMappings = [
{ "Name": 10%},
{ "Phone": 10%},
{ "Address": 50%},
{ "Zip": 10%},
{ "Comments": 20%}
]
I want to populate an HTML table later and want to set the titles of table to the first column of myMappings and the width of columns to the second. Is there a clean way to do it?
Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:
var myMappings = [
{ title: "Name", width: "10%" },
{ title: "Phone", width: "10%" },
{ title: "Address", width: "50%" },
{ title: "Zip", width: "10%" },
{ title: "Comments", width: "20%" }
];
Then you could easily iterate through all your "columns" with a for loop:
for (var i = 0; i < myMappings.length; i += 1) {
// myMappings[i].title ...
// myMappings[i].width ...
}
The main problem I see with what you have is that it's difficult to loop through, for populating a table.
Simply use an array of arrays:
var myMappings = [
["Name", "10%"], // Note the quotes around "10%"
["Phone", "10%"],
// etc..
];
... which simplifies access:
myMappings[0][0]; // column name
myMappings[0][1]; // column width
Alternatively:
var myMappings = {
names: ["Name", "Phone", etc...],
widths: ["10%", "10%", etc...]
};
And access with:
myMappings.names[0];
myMappings.widths[0];
An object technically is a dictionary.
var myMappings = {
mykey1: 'myValue',
mykey2: 'myValue'
};
var myVal = myMappings['myKey1'];
alert(myVal); // myValue
You can even loop through one.
for(var key in myMappings) {
var myVal = myMappings[key];
alert(myVal);
}
There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:
myMappings['mykey3'] = 'my value';
And ContainsKey:
if (myMappings.hasOwnProperty('myKey3')) {
alert('key already exists!');
}
I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/
You may be trying to use a JSON object:
var myMappings = { "name": "10%", "phone": "10%", "address": "50%", etc.. }
To access:
myMappings.name;
myMappings.phone;
etc..
Try:
var myMappings = {
"Name": "10%",
"Phone": "10%",
"Address": "50%",
"Zip": "10%",
"Comments": "20%"
}
// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above
// To loop through...
for(var title in myMappings) {
// Do whatever with myMappings[title]
}
I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:
var myMappings = {
"Name": 0.1,
"Phone": 0.1,
"Address": 0.5,
"Zip": 0.1,
"Comments": 0.2
};
for (var col in myMappings) {
alert((myMappings[col] * 100) + "%");
}
An easier, native and more efficient way of emulating a dict in JavaScript than a hash table:
It also exploits that JavaScript is weakly typed. Rather type inference.
Here's how (an excerpt from Google Chrome's console):
var myDict = {};
myDict.one = 1;
1
myDict.two = 2;
2
if (myDict.hasOwnProperty('three'))
{
console.log(myDict.two);
}
else
{
console.log('Key does not exist!');
}
Key does not exist! VM361:8
if (myDict.hasOwnProperty('two'))
{
console.log(myDict.two);
}
else
{
console.log('Key does not exist!');
}
2 VM362:4
Object.keys(myDict);
["one", "two"]
delete(myDict.two);
true
myDict.hasOwnProperty('two');
false
myDict.two
undefined
myDict.one
1
Here's a dictionary that will take any type of key as long as the toString() property returns unique values. The dictionary uses anything as the value for the key value pair.
See Would JavaScript Benefit from a Dictionary Object.
To use the dictionary as is:
var dictFact = new Dict();
var myDict = dictFact.New();
myDict.addOrUpdate("key1", "Value1");
myDict.addOrUpdate("key2", "Value2");
myDict.addOrUpdate("keyN", "ValueN");
The dictionary code is below:
/*
* Dictionary Factory Object
* Holds common object functions. similar to V-Table
* this.New() used to create new dictionary objects
* Uses Object.defineProperties so won't work on older browsers.
* Browser Compatibility (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)
* Firefox (Gecko) 4.0 (2), Chrome 5, Internet Explorer 9, Opera 11.60, Safari 5
*/
function Dict() {
/*
* Create a new Dictionary
*/
this.New = function () {
return new dict();
};
/*
* Return argument f if it is a function otherwise return undefined
*/
function ensureF(f) {
if (isFunct(f)) {
return f;
}
}
function isFunct(f) {
return (typeof f == "function");
}
/*
* Add a "_" as first character just to be sure valid property name
*/
function makeKey(k) {
return "_" + k;
};
/*
* Key Value Pair object - held in array
*/
function newkvp(key, value) {
return {
key: key,
value: value,
toString: function () { return this.key; },
valueOf: function () { return this.key; }
};
};
/*
* Return the current set of keys.
*/
function keys(a) {
// remove the leading "-" character from the keys
return a.map(function (e) { return e.key.substr(1); });
// Alternative: Requires Opera 12 vs. 11.60
// -- Must pass the internal object instead of the array
// -- Still need to remove the leading "-" to return user key values
// Object.keys(o).map(function (e) { return e.key.substr(1); });
};
/*
* Return the current set of values.
*/
function values(a) {
return a.map(function(e) { return e.value; } );
};
/*
* Return the current set of key value pairs.
*/
function kvPs(a) {
// Remove the leading "-" character from the keys
return a.map(function (e) { return newkvp(e.key.substr(1), e.value); });
}
/*
* Returns true if key exists in the dictionary.
* k - Key to check (with the leading "_" character)
*/
function exists(k, o) {
return o.hasOwnProperty(k);
}
/*
* Array Map implementation
*/
function map(a, f) {
if (!isFunct(f)) { return; }
return a.map(function (e, i) { return f(e.value, i); });
}
/*
* Array Every implementation
*/
function every(a, f) {
if (!isFunct(f)) { return; }
return a.every(function (e, i) { return f(e.value, i) });
}
/*
* Returns subset of "values" where function "f" returns true for the "value"
*/
function filter(a, f) {
if (!isFunct(f)) {return; }
var ret = a.filter(function (e, i) { return f(e.value, i); });
// if anything returned by array.filter, then get the "values" from the key value pairs
if (ret && ret.length > 0) {
ret = values(ret);
}
return ret;
}
/*
* Array Reverse implementation
*/
function reverse(a, o) {
a.reverse();
reindex(a, o, 0);
}
/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*/
function shuffle(a, o) {
var j, t;
for (var i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
t = a[i];
a[i] = a[j];
a[j] = t;
}
reindex(a, o, 0);
return a;
}
/*
* Array Some implementation
*/
function some(a, f) {
if (!isFunct(f)) { return; }
return a.some(function (e, i) { return f(e.value, i) });
}
/*
* Sort the dictionary. Sorts the array and reindexes the object.
* a - dictionary array
* o - dictionary object
* sf - dictionary default sort function (can be undefined)
* f - sort method sort function argument (can be undefined)
*/
function sort(a, o, sf, f) {
var sf1 = f || sf; // sort function method used if not undefined
// if there is a customer sort function, use it
if (isFunct(sf1)) {
a.sort(function (e1, e2) { return sf1(e1.value, e2.value); });
}
else {
// sort by key values
a.sort();
}
// reindex - adds O(n) to perf
reindex(a, o, 0);
// return sorted values (not entire array)
// adds O(n) to perf
return values(a);
};
/*
* forEach iteration of "values"
* uses "for" loop to allow exiting iteration when function returns true
*/
function forEach(a, f) {
if (!isFunct(f)) { return; }
// use for loop to allow exiting early and not iterating all items
for(var i = 0; i < a.length; i++) {
if (f(a[i].value, i)) { break; }
}
};
/*
* forEachR iteration of "values" in reverse order
* uses "for" loop to allow exiting iteration when function returns true
*/
function forEachR(a, f) {
if (!isFunct(f)) { return; }
// use for loop to allow exiting early and not iterating all items
for (var i = a.length - 1; i > -1; i--) {
if (f(a[i].value, i)) { break; }
}
}
/*
* Add a new Key Value Pair, or update the value of an existing key value pair
*/
function add(key, value, a, o, resort, sf) {
var k = makeKey(key);
// Update value if key exists
if (exists(k, o)) {
a[o[k]].value = value;
}
else {
// Add a new Key value Pair
var kvp = newkvp(k, value);
o[kvp.key] = a.length;
a.push(kvp);
}
// resort if requested
if (resort) { sort(a, o, sf); }
};
/*
* Removes an existing key value pair and returns the "value" If the key does not exists, returns undefined
*/
function remove(key, a, o) {
var k = makeKey(key);
// return undefined if the key does not exist
if (!exists(k, o)) { return; }
// get the array index
var i = o[k];
// get the key value pair
var ret = a[i];
// remove the array element
a.splice(i, 1);
// remove the object property
delete o[k];
// reindex the object properties from the remove element to end of the array
reindex(a, o, i);
// return the removed value
return ret.value;
};
/*
* Returns true if key exists in the dictionary.
* k - Key to check (without the leading "_" character)
*/
function keyExists(k, o) {
return exists(makeKey(k), o);
};
/*
* Returns value assocated with "key". Returns undefined if key not found
*/
function item(key, a, o) {
var k = makeKey(key);
if (exists(k, o)) {
return a[o[k]].value;
}
}
/*
* changes index values held by object properties to match the array index location
* Called after sorting or removing
*/
function reindex(a, o, i){
for (var j = i; j < a.length; j++) {
o[a[j].key] = j;
}
}
/*
* The "real dictionary"
*/
function dict() {
var _a = [];
var _o = {};
var _sortF;
Object.defineProperties(this, {
"length": { get: function () { return _a.length; }, enumerable: true },
"keys": { get: function() { return keys(_a); }, enumerable: true },
"values": { get: function() { return values(_a); }, enumerable: true },
"keyValuePairs": { get: function() { return kvPs(_a); }, enumerable: true},
"sortFunction": { get: function() { return _sortF; }, set: function(funct) { _sortF = ensureF(funct); }, enumerable: true }
});
// Array Methods - Only modification to not pass the actual array to the callback function
this.map = function(funct) { return map(_a, funct); };
this.every = function(funct) { return every(_a, funct); };
this.filter = function(funct) { return filter(_a, funct); };
this.reverse = function() { reverse(_a, _o); };
this.shuffle = function () { return shuffle(_a, _o); };
this.some = function(funct) { return some(_a, funct); };
this.sort = function(funct) { return sort(_a, _o, _sortF, funct); };
// Array Methods - Modified aborts when funct returns true.
this.forEach = function (funct) { forEach(_a, funct) };
// forEach in reverse order
this.forEachRev = function (funct) { forEachR(_a, funct) };
// Dictionary Methods
this.addOrUpdate = function(key, value, resort) { return add(key, value, _a, _o, resort, _sortF); };
this.remove = function(key) { return remove(key, _a, _o); };
this.exists = function(key) { return keyExists(key, _o); };
this.item = function(key) { return item(key, _a, _o); };
this.get = function (index) { if (index > -1 && index < _a.length) { return _a[index].value; } } ,
this.clear = function() { _a = []; _o = {}; };
return this;
}
return this;
}
Related
I threw some code together to flatten and un-flatten complex/nested JavaScript objects. It works, but it's a bit slow (triggers the 'long script' warning).
For the flattened names I want "." as the delimiter and [INDEX] for arrays.
Examples:
un-flattened | flattened
---------------------------
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
[1,[2,[3,4],5],6] => {"[0]":1,"[1].[0]":2,"[1].[1].[0]":3,"[1].[1].[1]":4,"[1].[2]":5,"[2]":6}
I created a benchmark that ~simulates my use case http://jsfiddle.net/WSzec/
Get a nested object
Flatten it
Look through it and possibly modify it while flattened
Unflatten it back to it's original nested format to be shipped away
I would like faster code: For clarification, code that completes the JSFiddle benchmark (http://jsfiddle.net/WSzec/) significantly faster (~20%+ would be nice) in IE 9+, FF 24+, and Chrome 29+.
Here's the relevant JavaScript code: Current Fastest: http://jsfiddle.net/WSzec/6/
var unflatten = function(data) {
"use strict";
if (Object(data) !== data || Array.isArray(data))
return data;
var result = {}, cur, prop, idx, last, temp;
for(var p in data) {
cur = result, prop = "", last = 0;
do {
idx = p.indexOf(".", last);
temp = p.substring(last, idx !== -1 ? idx : undefined);
cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {}));
prop = temp;
last = idx + 1;
} while(idx >= 0);
cur[prop] = data[p];
}
return result[""];
}
var flatten = function(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop ? prop+"."+i : ""+i);
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty)
result[prop] = {};
}
}
recurse(data, "");
return result;
}
EDIT 1 Modified the above to #Bergi 's implementation which is currently the fastest. As an aside, using ".indexOf" instead of "regex.exec" is around 20% faster in FF but 20% slower in Chrome; so I'll stick with the regex since it's simpler (here's my attempt at using indexOf to replace the regex http://jsfiddle.net/WSzec/2/).
EDIT 2 Building on #Bergi 's idea I managed to created a faster non-regex version (3x faster in FF and ~10% faster in Chrome). http://jsfiddle.net/WSzec/6/ In the this (the current) implementation the rules for key names are simply, keys cannot start with an integer or contain a period.
Example:
{"foo":{"bar":[0]}} => {"foo.bar.0":0}
EDIT 3 Adding #AaditMShah 's inline path parsing approach (rather than String.split) helped to improve the unflatten performance. I'm very happy with the overall performance improvement reached.
The latest jsfiddle and jsperf:
http://jsfiddle.net/WSzec/14/
http://jsperf.com/flatten-un-flatten/4
Here's my much shorter implementation:
Object.unflatten = function(data) {
"use strict";
if (Object(data) !== data || Array.isArray(data))
return data;
var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
resultholder = {};
for (var p in data) {
var cur = resultholder,
prop = "",
m;
while (m = regex.exec(p)) {
cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
prop = m[2] || m[1];
}
cur[prop] = data[p];
}
return resultholder[""] || resultholder;
};
flatten hasn't changed much (and I'm not sure whether you really need those isEmpty cases):
Object.flatten = function(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(data, "");
return result;
}
Together, they run your benchmark in about the half of the time (Opera 12.16: ~900ms instead of ~ 1900ms, Chrome 29: ~800ms instead of ~1600ms).
Note: This and most other solutions answered here focus on speed and are susceptible to prototype pollution and shold not be used on untrusted objects.
I wrote two functions to flatten and unflatten a JSON object.
Flatten a JSON object:
var flatten = (function (isArray, wrapped) {
return function (table) {
return reduce("", {}, table);
};
function reduce(path, accumulator, table) {
if (isArray(table)) {
var length = table.length;
if (length) {
var index = 0;
while (index < length) {
var property = path + "[" + index + "]", item = table[index++];
if (wrapped(item) !== item) accumulator[property] = item;
else reduce(property, accumulator, item);
}
} else accumulator[path] = table;
} else {
var empty = true;
if (path) {
for (var property in table) {
var item = table[property], property = path + "." + property, empty = false;
if (wrapped(item) !== item) accumulator[property] = item;
else reduce(property, accumulator, item);
}
} else {
for (var property in table) {
var item = table[property], empty = false;
if (wrapped(item) !== item) accumulator[property] = item;
else reduce(property, accumulator, item);
}
}
if (empty) accumulator[path] = table;
}
return accumulator;
}
}(Array.isArray, Object));
Performance:
It's faster than the current solution in Opera. The current solution is 26% slower in Opera.
It's faster than the current solution in Firefox. The current solution is 9% slower in Firefox.
It's faster than the current solution in Chrome. The current solution is 29% slower in Chrome.
Unflatten a JSON object:
function unflatten(table) {
var result = {};
for (var path in table) {
var cursor = result, length = path.length, property = "", index = 0;
while (index < length) {
var char = path.charAt(index);
if (char === "[") {
var start = index + 1,
end = path.indexOf("]", start),
cursor = cursor[property] = cursor[property] || [],
property = path.slice(start, end),
index = end + 1;
} else {
var cursor = cursor[property] = cursor[property] || {},
start = char === "." ? index + 1 : index,
bracket = path.indexOf("[", start),
dot = path.indexOf(".", start);
if (bracket < 0 && dot < 0) var end = index = length;
else if (bracket < 0) var end = index = dot;
else if (dot < 0) var end = index = bracket;
else var end = index = bracket < dot ? bracket : dot;
var property = path.slice(start, end);
}
}
cursor[property] = table[path];
}
return result[""];
}
Performance:
It's faster than the current solution in Opera. The current solution is 5% slower in Opera.
It's slower than the current solution in Firefox. My solution is 26% slower in Firefox.
It's slower than the current solution in Chrome. My solution is 6% slower in Chrome.
Flatten and unflatten a JSON object:
Overall my solution performs either equally well or even better than the current solution.
Performance:
It's faster than the current solution in Opera. The current solution is 21% slower in Opera.
It's as fast as the current solution in Firefox.
It's faster than the current solution in Firefox. The current solution is 20% slower in Chrome.
Output format:
A flattened object uses the dot notation for object properties and the bracket notation for array indices:
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
[1,[2,[3,4],5],6] => {"[0]":1,"[1][0]":2,"[1][1][0]":3,"[1][1][1]":4,"[1][2]":5,"[2]":6}
In my opinion this format is better than only using the dot notation:
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a.0.b.0":"c","a.0.b.1":"d"}
[1,[2,[3,4],5],6] => {"0":1,"1.0":2,"1.1.0":3,"1.1.1":4,"1.2":5,"2":6}
Advantages:
Flattening an object is faster than the current solution.
Flattening and unflattening an object is as fast as or faster than the current solution.
Flattened objects use both the dot notation and the bracket notation for readability.
Disadvantages:
Unflattening an object is slower than the current solution in most (but not all) cases.
The current JSFiddle demo gave the following values as output:
Nested : 132175 : 63
Flattened : 132175 : 564
Nested : 132175 : 54
Flattened : 132175 : 508
My updated JSFiddle demo gave the following values as output:
Nested : 132175 : 59
Flattened : 132175 : 514
Nested : 132175 : 60
Flattened : 132175 : 451
I'm not really sure what that means, so I'll stick with the jsPerf results. After all jsPerf is a performance benchmarking utility. JSFiddle is not.
ES6 version:
const flatten = (obj, path = '') => {
if (!(obj instanceof Object)) return {[path.replace(/\.$/g, '')]:obj};
return Object.keys(obj).reduce((output, key) => {
return obj instanceof Array ?
{...output, ...flatten(obj[key], path + '[' + key + '].')}:
{...output, ...flatten(obj[key], path + key + '.')};
}, {});
}
Example:
console.log(flatten({a:[{b:["c","d"]}]}));
console.log(flatten([1,[2,[3,4],5],6]));
3 ½ Years later...
For my own project I wanted to flatten JSON objects in mongoDB dot notation and came up with a simple solution:
/**
* Recursively flattens a JSON object using dot notation.
*
* NOTE: input must be an object as described by JSON spec. Arbitrary
* JS objects (e.g. {a: () => 42}) may result in unexpected output.
* MOREOVER, it removes keys with empty objects/arrays as value (see
* examples bellow).
*
* #example
* // returns {a:1, 'b.0.c': 2, 'b.0.d.e': 3, 'b.1': 4}
* flatten({a: 1, b: [{c: 2, d: {e: 3}}, 4]})
* // returns {a:1, 'b.0.c': 2, 'b.0.d.e.0': true, 'b.0.d.e.1': false, 'b.0.d.e.2.f': 1}
* flatten({a: 1, b: [{c: 2, d: {e: [true, false, {f: 1}]}}]})
* // return {a: 1}
* flatten({a: 1, b: [], c: {}})
*
* #param obj item to be flattened
* #param {Array.string} [prefix=[]] chain of prefix joined with a dot and prepended to key
* #param {Object} [current={}] result of flatten during the recursion
*
* #see https://docs.mongodb.com/manual/core/document/#dot-notation
*/
function flatten (obj, prefix, current) {
prefix = prefix || []
current = current || {}
// Remember kids, null is also an object!
if (typeof (obj) === 'object' && obj !== null) {
Object.keys(obj).forEach(key => {
this.flatten(obj[key], prefix.concat(key), current)
})
} else {
current[prefix.join('.')] = obj
}
return current
}
Features and/or caveats
It only accepts JSON objects. So if you pass something like {a: () => {}} you might not get what you wanted!
It removes empty arrays and objects. So this {a: {}, b: []} is flattened to {}.
Use this library:
npm install flat
Usage (from https://www.npmjs.com/package/flat):
Flatten:
var flatten = require('flat')
flatten({
key1: {
keyA: 'valueI'
},
key2: {
keyB: 'valueII'
},
key3: { a: { b: { c: 2 } } }
})
// {
// 'key1.keyA': 'valueI',
// 'key2.keyB': 'valueII',
// 'key3.a.b.c': 2
// }
Un-flatten:
var unflatten = require('flat').unflatten
unflatten({
'three.levels.deep': 42,
'three.levels': {
nested: true
}
})
// {
// three: {
// levels: {
// deep: 42,
// nested: true
// }
// }
// }
Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)
Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.
JSON.unflatten = function(data) {
"use strict";
if (Object(data) !== data || Array.isArray(data))
return data;
var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
props = Object.keys(data),
result, p;
while(p = props.shift()) {
var m = regex.exec(p),
target;
if (m.index) {
var rest = p.slice(0, m.index);
if (!(rest in data)) {
data[rest] = m[2] ? [] : {};
props.push(rest);
}
target = data[rest];
} else {
target = result || (result = (m[2] ? [] : {}));
}
target[m[2] || m[1]] = data[p];
}
return result;
};
It currently uses the data input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf usage performs better than the regex (depends on the regex engine).
See it in action here.
You can use https://github.com/hughsk/flat
Take a nested Javascript object and flatten it, or unflatten an object with delimited keys.
Example from the doc
var flatten = require('flat')
flatten({
key1: {
keyA: 'valueI'
},
key2: {
keyB: 'valueII'
},
key3: { a: { b: { c: 2 } } }
})
// {
// 'key1.keyA': 'valueI',
// 'key2.keyB': 'valueII',
// 'key3.a.b.c': 2
// }
var unflatten = require('flat').unflatten
unflatten({
'three.levels.deep': 42,
'three.levels': {
nested: true
}
})
// {
// three: {
// levels: {
// deep: 42,
// nested: true
// }
// }
// }
This code recursively flattens out JSON objects.
I included my timing mechanism in the code and it gives me 1ms but I'm not sure if that's the most accurate one.
var new_json = [{
"name": "fatima",
"age": 25,
"neighbour": {
"name": "taqi",
"location": "end of the street",
"property": {
"built in": 1990,
"owned": false,
"years on market": [1990, 1998, 2002, 2013],
"year short listed": [], //means never
}
},
"town": "Mountain View",
"state": "CA"
},
{
"name": "qianru",
"age": 20,
"neighbour": {
"name": "joe",
"location": "opposite to the park",
"property": {
"built in": 2011,
"owned": true,
"years on market": [1996, 2011],
"year short listed": [], //means never
}
},
"town": "Pittsburgh",
"state": "PA"
}]
function flatten(json, flattened, str_key) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (json[key] instanceof Object && json[key] != "") {
flatten(json[key], flattened, str_key + "." + key);
} else {
flattened[str_key + "." + key] = json[key];
}
}
}
}
var flattened = {};
console.time('flatten');
flatten(new_json, flattened, "");
console.timeEnd('flatten');
for (var key in flattened){
console.log(key + ": " + flattened[key]);
}
Output:
flatten: 1ms
.0.name: fatima
.0.age: 25
.0.neighbour.name: taqi
.0.neighbour.location: end of the street
.0.neighbour.property.built in: 1990
.0.neighbour.property.owned: false
.0.neighbour.property.years on market.0: 1990
.0.neighbour.property.years on market.1: 1998
.0.neighbour.property.years on market.2: 2002
.0.neighbour.property.years on market.3: 2013
.0.neighbour.property.year short listed:
.0.town: Mountain View
.0.state: CA
.1.name: qianru
.1.age: 20
.1.neighbour.name: joe
.1.neighbour.location: opposite to the park
.1.neighbour.property.built in: 2011
.1.neighbour.property.owned: true
.1.neighbour.property.years on market.0: 1996
.1.neighbour.property.years on market.1: 2011
.1.neighbour.property.year short listed:
.1.town: Pittsburgh
.1.state: PA
Here's mine. It runs in <2ms in Google Apps Script on a sizable object. It uses dashes instead of dots for separators, and it doesn't handle arrays specially like in the asker's question, but this is what I wanted for my use.
function flatten (obj) {
var newObj = {};
for (var key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
var temp = flatten(obj[key])
for (var key2 in temp) {
newObj[key+"-"+key2] = temp[key2];
}
} else {
newObj[key] = obj[key];
}
}
return newObj;
}
Example:
var test = {
a: 1,
b: 2,
c: {
c1: 3.1,
c2: 3.2
},
d: 4,
e: {
e1: 5.1,
e2: 5.2,
e3: {
e3a: 5.31,
e3b: 5.32
},
e4: 5.4
},
f: 6
}
Logger.log("start");
Logger.log(JSON.stringify(flatten(test),null,2));
Logger.log("done");
Example output:
[17-02-08 13:21:05:245 CST] start
[17-02-08 13:21:05:246 CST] {
"a": 1,
"b": 2,
"c-c1": 3.1,
"c-c2": 3.2,
"d": 4,
"e-e1": 5.1,
"e-e2": 5.2,
"e-e3-e3a": 5.31,
"e-e3-e3b": 5.32,
"e-e4": 5.4,
"f": 6
}
[17-02-08 13:21:05:247 CST] done
Object.prototype.flatten = function (obj) {
let ans = {};
let anotherObj = { ...obj };
function performFlatten(anotherObj) {
Object.keys(anotherObj).forEach((key, idx) => {
if (typeof anotherObj[key] !== 'object') {
ans[key] = anotherObj[key];
console.log('ans so far : ', ans);
} else {
console.log(key, { ...anotherObj[key] });
performFlatten(anotherObj[key]);
}
})
}
performFlatten(anotherObj);
return ans;
}
let ans = flatten(obj);
console.log(ans);
I added +/- 10-15% efficiency to the selected answer by minor code refactoring and moving the recursive function outside of the function namespace.
See my question: Are namespaced functions reevaluated on every call? for why this slows nested functions down.
function _flatten (target, obj, path) {
var i, empty;
if (obj.constructor === Object) {
empty = true;
for (i in obj) {
empty = false;
_flatten(target, obj[i], path ? path + '.' + i : i);
}
if (empty && path) {
target[path] = {};
}
}
else if (obj.constructor === Array) {
i = obj.length;
if (i > 0) {
while (i--) {
_flatten(target, obj[i], path + '[' + i + ']');
}
} else {
target[path] = [];
}
}
else {
target[path] = obj;
}
}
function flatten (data) {
var result = {};
_flatten(result, data, null);
return result;
}
See benchmark.
Here's a recursive solution for flatten I put together in PowerShell:
#---helper function for ConvertTo-JhcUtilJsonTable
#
function getNodes {
param (
[Parameter(Mandatory)]
[System.Object]
$job,
[Parameter(Mandatory)]
[System.String]
$path
)
$t = $job.GetType()
$ct = 0
$h = #{}
if ($t.Name -eq 'PSCustomObject') {
foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
}
}
elseif ($t.Name -eq 'Object[]') {
foreach ($o in $job) {
getNodes -job $o -path ($path + "[$ct]")
$ct++
}
}
else {
$h[$path] = $job
$h
}
}
#---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
#
function ConvertTo-JhcUtilJsonTable {
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[System.Object[]]
$jsonObj
)
begin {
$rootNode = 'root'
}
process {
foreach ($o in $jsonObj) {
$table = getNodes -job $o -path $rootNode
# $h = #{}
$a = #()
$pat = '^' + $rootNode
foreach ($i in $table) {
foreach ($k in $i.keys) {
# $h[$k -replace $pat, ''] = $i[$k]
$a += New-Object -TypeName psobject -Property #{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
# $h[$k -replace $pat, ''] = $i[$k]
}
}
# $h
$a
}
}
end{}
}
Example:
'{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
Key Value
--- -----
.Address.house 1234
.Address.Street Boogie Ave
.name John
.pets[0].Age 4
.pets[0].Toys[0] rubberBall
.pets[0].Toys[1] rope
.pets[0].Type Dog
.pets[1].Age 7
.pets[1].Toys[0] catNip
.pets[1].Type Cat
I wanted an approach so that I could be able to easily convert my json data into a csv file.
The scenario is: I query data from somewhere and I receive an array of some model, like a bank extract.
This approach below is used to parse each one of these entries.
function jsonFlatter(data, previousKey, obj) {
obj = obj || {}
previousKey = previousKey || ""
Object.keys(data).map(key => {
let newKey = `${previousKey}${previousKey ? "_" : ""}${key}`
let _value = data[key]
let isArray = Array.isArray(_value)
if (typeof _value !== "object" || isArray || _value == null) {
if (isArray) {
_value = JSON.stringify(_value)
} else if (_value == null) {
_value = "null"
}
obj[newKey] = _value
} else if (typeof _value === "object") {
if (!Object.keys(_value).length) {
obj[newKey] = "null"
} else {
return jsonFlatter(_value, newKey, obj)
}
}
})
return obj
}
This way, I can count on the uniformity of the keys and inner keys of my object model, but arrays are simply stringified since I can't rely on their uniformity. Also, empty objects become the string "null", since I still want it's key to appear in the final result.
Usage example:
const test_data = {
a: {
aa: {
aaa: 4354,
aab: 654
},
ab: 123
},
b: 234,
c: {},
d: []
}
console.log('result', jsonFlatter(test_data))
#### output
{
"a_aa_aaa": 4354,
"a_aa_aab": 654,
"a_ab": 123,
"b": 234,
"c": "null",
"d": "[]"
}
try this one:
function getFlattenObject(data, response = {}) {
for (const key in data) {
if (typeof data[key] === 'object' && !Array.isArray(data[key])) {
getFlattenObject(data[key], response);
} else {
response[key] = data[key];
}
}
return response;
}
I'd like to add a new version of flatten case (this is what i needed :)) which, according to my probes with the above jsFiddler, is slightly faster then the currently selected one.
Moreover, me personally see this snippet a bit more readable, which is of course important for multi-developer projects.
function flattenObject(graph) {
let result = {},
item,
key;
function recurr(graph, path) {
if (Array.isArray(graph)) {
graph.forEach(function (itm, idx) {
key = path + '[' + idx + ']';
if (itm && typeof itm === 'object') {
recurr(itm, key);
} else {
result[key] = itm;
}
});
} else {
Reflect.ownKeys(graph).forEach(function (p) {
key = path + '.' + p;
item = graph[p];
if (item && typeof item === 'object') {
recurr(item, key);
} else {
result[key] = item;
}
});
}
}
recurr(graph, '');
return result;
}
Here is some code I wrote to flatten an object I was working with. It creates a new class that takes every nested field and brings it into the first layer. You could modify it to unflatten by remembering the original placement of the keys. It also assumes the keys are unique even across nested objects. Hope it helps.
class JSONFlattener {
ojson = {}
flattenedjson = {}
constructor(original_json) {
this.ojson = original_json
this.flattenedjson = {}
this.flatten()
}
flatten() {
Object.keys(this.ojson).forEach(function(key){
if (this.ojson[key] == null) {
} else if (this.ojson[key].constructor == ({}).constructor) {
this.combine(new JSONFlattener(this.ojson[key]).returnJSON())
} else {
this.flattenedjson[key] = this.ojson[key]
}
}, this)
}
combine(new_json) {
//assumes new_json is a flat array
Object.keys(new_json).forEach(function(key){
if (!this.flattenedjson.hasOwnProperty(key)) {
this.flattenedjson[key] = new_json[key]
} else {
console.log(key+" is a duplicate key")
}
}, this)
}
returnJSON() {
return this.flattenedjson
}
}
console.log(new JSONFlattener(dad_dictionary).returnJSON())
As an example, it converts
nested_json = {
"a": {
"b": {
"c": {
"d": {
"a": 0
}
}
}
},
"z": {
"b":1
},
"d": {
"c": {
"c": 2
}
}
}
into
{ a: 0, b: 1, c: 2 }
You can try out the package jpflat.
It flattens, inflates, resolves promises, flattens arrays, has customizable path creation and customizable value serialization.
The reducers and serializers receive the whole path as an array of it's parts, so more complex operations can be done to the path instead of modifying a single key or changing the delimiter.
Json path is the default, hence "jp"flat.
https://www.npmjs.com/package/jpflat
let flatFoo = await require('jpflat').flatten(foo)
I'm not from a programming background but I have a requirement in that I need to be able to convert excel data to JSON format.
I have found the below package which is exactly what I need as I can control the object types from the header names rather than hard code for each field. It also allows me to column orientate my data i.e. the header in column A.
The package can be found here --> excel-as-json
The output looks like this:
[
{
"firstName": "Jihad",
"lastName": "",
"address": {
"street": "12 Beaver Court",
"city": "",
"state": "CO",
"zip": "81615"
},
"isEmployee": true,
"phones": [
{
"type": "home",
"number": "123.456.7890"
},
{
"type": "work",
"number": "098.765.4321"
}
],
"aliases": [
"stormagedden",
"bob"
]
},
{
"firstName": "Marcus",
"lastName": "Rivapoli",
"address": {
"street": "16 Vail Rd",
"city": "Vail",
"state": "CO",
"zip": "75850"
},
"isEmployee": false,
"phones": [
{
"type": "home",
"number": "123.456.7891"
},
{
"type": "work",
"number": "098.765.4322"
}
],
"aliases": [
"mac",
"markie"
]
}
]
What I need to do and what I'm struggling with is two fold:
I need to remove the square brackets from the beginning and end of the generated JSON
I need to be able to generate multiple JSONs i.e. a JSON for each column of data. So if I have data in column B and C, I need it to generate 2 JSON files with different names (ideally with the name of a specific attribute value)
The code is:
// Generated by CoffeeScript 2.2.4
(function() {
// Create a list of json objects; 1 object per excel sheet row
// Assume: Excel spreadsheet is a rectangle of data, where the first row is
// object keys and remaining rows are object values and the desired json
// is a list of objects. Alternatively, data may be column oriented with
// col 0 containing key names.
// Dotted notation: Key row (0) containing firstName, lastName, address.street,
// address.city, address.state, address.zip would produce, per row, a doc with
// first and last names and an embedded doc named address, with the address.
// Arrays: may be indexed (phones[0].number) or flat (aliases[]). Indexed
// arrays imply a list of objects. Flat arrays imply a semicolon delimited list.
// USE:
// From a shell
// coffee src/excel-as-json.coffee
var BOOLTEXT, BOOLVALS, _DEFAULT_OPTIONS, _validateOptions, assign, convert, convertValue, convertValueList, excel, fs, isArray, parseKeyName, path, processFile, transpose, write,
indexOf = [].indexOf;
fs = require('fs');
path = require('path');
excel = require('excel');
BOOLTEXT = ['true', 'false'];
BOOLVALS = {
'true': true,
'false': false
};
isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
// Extract key name and array index from names[1] or names[]
// return [keyIsList, keyName, index]
// for names[1] return [true, keyName, index]
// for names[] return [true, keyName, undefined]
// for names return [false, keyName, undefined]
parseKeyName = function(key) {
var index;
index = key.match(/\[(\d+)\]$/);
switch (false) {
case !index:
return [true, key.split('[')[0], Number(index[1])];
case key.slice(-2) !== '[]':
return [true, key.slice(0, -2), void 0];
default:
return [false, key, void 0];
}
};
// Convert a list of values to a list of more native forms
convertValueList = function(list, options) {
var item, j, len, results;
results = [];
for (j = 0, len = list.length; j < len; j++) {
item = list[j];
results.push(convertValue(item, options));
}
return results;
};
// Convert values to native types
// Note: all values from the excel module are text
convertValue = function(value, options) {
var testVal;
// isFinite returns true for empty or blank strings, check for those first
if (value.length === 0 || !/\S/.test(value)) {
return value;
} else if (isFinite(value)) {
if (options.convertTextToNumber) {
return Number(value);
} else {
return value;
}
} else {
testVal = value.toLowerCase();
if (indexOf.call(BOOLTEXT, testVal) >= 0) {
return BOOLVALS[testVal];
} else {
return value;
}
}
};
// Assign a value to a dotted property key - set values on sub-objects
assign = function(obj, key, value, options) {
var i, index, j, keyIsList, keyName, ref, ref1;
if (typeof key !== 'object') {
// On first call, a key is a string. Recursed calls, a key is an array
key = key.split('.');
}
// Array element accessors look like phones[0].type or aliases[]
[keyIsList, keyName, index] = parseKeyName(key.shift());
if (key.length) {
if (keyIsList) {
// if our object is already an array, ensure an object exists for this index
if (isArray(obj[keyName])) {
if (!obj[keyName][index]) {
for (i = j = ref = obj[keyName].length, ref1 = index; (ref <= ref1 ? j <= ref1 : j >= ref1); i = ref <= ref1 ? ++j : --j) {
obj[keyName].push({});
}
}
} else {
// else set this value to an array large enough to contain this index
obj[keyName] = (function() {
var k, ref2, results;
results = [];
for (i = k = 0, ref2 = index; (0 <= ref2 ? k <= ref2 : k >= ref2); i = 0 <= ref2 ? ++k : --k) {
results.push({});
}
return results;
})();
}
return assign(obj[keyName][index], key, value, options);
} else {
if (obj[keyName] == null) {
obj[keyName] = {};
}
return assign(obj[keyName], key, value, options);
}
} else {
if (keyIsList && (index != null)) {
console.error(`WARNING: Unexpected key path terminal containing an indexed list for <${keyName}>`);
console.error("WARNING: Indexed arrays indicate a list of objects and should not be the last element in a key path");
console.error("WARNING: The last element of a key path should be a key name or flat array. E.g. alias, aliases[]");
}
if (keyIsList && (index == null)) {
if (value !== '') {
return obj[keyName] = convertValueList(value.split(';'), options);
} else if (!options.omitEmptyFields) {
return obj[keyName] = [];
}
} else {
if (!(options.omitEmptyFields && value === '')) {
return obj[keyName] = convertValue(value, options);
}
}
}
};
// Transpose a 2D array
transpose = function(matrix) {
var i, j, ref, results, t;
results = [];
for (i = j = 0, ref = matrix[0].length; (0 <= ref ? j < ref : j > ref); i = 0 <= ref ? ++j : --j) {
results.push((function() {
var k, len, results1;
results1 = [];
for (k = 0, len = matrix.length; k < len; k++) {
t = matrix[k];
results1.push(t[i]);
}
return results1;
})());
}
return results;
};
// Convert 2D array to nested objects. If row oriented data, row 0 is dotted key names.
// Column oriented data is transposed
convert = function(data, options) {
var index, item, j, k, keys, len, len1, result, row, rows, value;
if (options.isColOriented) {
data = transpose(data);
}
keys = data[0];
rows = data.slice(1);
result = [];
for (j = 0, len = rows.length; j < len; j++) {
row = rows[j];
item = [];
for (index = k = 0, len1 = row.length; k < len1; index = ++k) {
value = row[index];
assign(item, keys[index], value, options);
}
result.push(item);
}
return result;
};
// Write JSON encoded data to file
// call back is callback(err)
write = function(data, dst, callback) {
var dir;
// Create the target directory if it does not exist
dir = path.dirname(dst);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
return fs.writeFile(dst, JSON.stringify(data, null, 2), function(err) {
if (err) {
return callback(`Error writing file ${dst}: ${err}`);
} else {
return callback(void 0);
}
});
};
// src: xlsx file that we will read sheet 0 of
// dst: file path to write json to. If null, simply return the result
// options: see below
// callback(err, data): callback for completion notification
// options:
// sheet: string; 1: numeric, 1-based index of target sheet
// isColOriented: boolean: false; are objects stored in excel columns; key names in col A
// omitEmptyFields: boolean: false: do not include keys with empty values in json output. empty values are stored as ''
// TODO: this is probably better named omitKeysWithEmptyValues
// convertTextToNumber boolean: true; if text looks like a number, convert it to a number
// convertExcel(src, dst) <br/>
// will write a row oriented xlsx sheet 1 to `dst` as JSON with no notification
// convertExcel(src, dst, {isColOriented: true}) <br/>
// will write a col oriented xlsx sheet 1 to file with no notification
// convertExcel(src, dst, {isColOriented: true}, callback) <br/>
// will write a col oriented xlsx to file and notify with errors and parsed data
// convertExcel(src, null, null, callback) <br/>
// will parse a row oriented xslx using default options and return errors and the parsed data in the callback
_DEFAULT_OPTIONS = {
sheet: '1',
isColOriented: false,
omitEmptyFields: false,
convertTextToNumber: false
};
// Ensure options sane, provide defaults as appropriate
_validateOptions = function(options) {
if (!options) {
options = _DEFAULT_OPTIONS;
} else {
if (!options.hasOwnProperty('sheet')) {
options.sheet = '1';
} else {
if (!isNaN(parseFloat(options.sheet)) && isFinite(options.sheet)) {
if (options.sheet < 1) {
options.sheet = '1';
} else {
// could be 3 or '3'; force to be '3'
options.sheet = '' + options.sheet;
}
} else {
// something bizarre like true, [Function: isNaN], etc
options.sheet = '1';
}
}
if (!options.hasOwnProperty('isColOriented')) {
options.isColOriented = false;
}
if (!options.hasOwnProperty('omitEmptyFields')) {
options.omitEmptyFields = false;
}
if (!options.hasOwnProperty('convertTextToNumber')) {
options.convertTextToNumber = false;
}
}
return options;
};
processFile = function(src, dst, options = _DEFAULT_OPTIONS, callback = void 0) {
options = _validateOptions(options);
if (!callback) {
callback = function(err, data) {};
}
// NOTE: 'excel' does not properly bubble file not found and prints
// an ugly error we can't trap, so look for this common error first
if (!fs.existsSync(src)) {
return callback(`Cannot find src file ${src}`);
} else {
return excel(src, options.sheet, function(err, data) {
var result;
if (err) {
return callback(`Error reading ${src}: ${err}`);
} else {
result = convert(data, options);
if (dst) {
return write(result, dst, function(err) {
if (err) {
return callback(err);
} else {
return callback(void 0, result);
}
});
} else {
return callback(void 0, result);
}
}
});
}
};
// This is the single expected module entry point
exports.processFile = processFile;
// Unsupported use
// Exposing remaining functionality for unexpected use cases, testing, etc.
exports.assign = assign;
exports.convert = convert;
exports.convertValue = convertValue;
exports.parseKeyName = parseKeyName;
exports._validateOptions = _validateOptions;
exports.transpose = transpose;
}).call(this);
This is untested, but should get you close.
Try adding a function like this into the code (along with the other listed functions, like isArray, parseKeyName, etc.). Then in the processFile function, in the line return write(result, dst, function(err) {, replace write with writeEach.
See the comments in the code for clarification of what it's intended to do.
writeEach = function(data, dst, callback){
// Loops through columns, calling fs.writeFile for each one
data.forEach(function(person){ // argument name determines the name by which we will refer to the current column
var homePhoneDigits = person.phones[0]["number"].split(".").join(""); //removes `.` from phone number
var personDst = homePhoneDigits + ".json"; // uses digits of home phone as destination name
// pattern copied from 'write' function, with variable names changed
var dir;
dir = path.dirname(personDst);
if (!fs.existsSync(dir)) { fs.mkdirSync(dir); }
fs.writeFile(personDst, JSON.stringify(person, null, 2); //writes the current column to a file
});
return callback(void 0); // currently ignores any write errors
};
I've been able to cook up a Radix tree example in JavaScript (not optimised, so don't judge)
So far I have been able to Add, Transverse and Find nodes.
I'm having trouble writing a function that can retrieve all nodes, this is where I require assistance.Thank you in advance
// As illustrated in:
// http://programminggeeks.com/c-code-for-radix-tree-or-trie/
// Make a class of the Tree so that you can define methods all nodes of the tree
// which are actually Trees in structure inherit the functions
function Tree() {
this.character = undefined;
// if this node is the end of a complete word
// this was we can differentiate "sell" and "sells" if both are searched for
this.isword = false;
// How to nest the nodes, thus creating a tree structure
this.node = {}; // [new Tree(), new Tree(), new Tree()];
// abcdefghijklmnopqrstuvwxyz
var start = 97,
end = start + 25;
function constructor(that) {
for (var x = start; x <= end; x++) {
// for now they are all unsigned objects
that.node[x] = null // new Tree()
}
return that;
}
constructor(this);
return this;
}
Tree.prototype.addNode = function(word) {
return this.transverseNodes(word, true);
};
Tree.prototype.searchForNodes = function(word) {
return this.transverseNodes(word, false);
};
Tree.prototype.stringToNodes = function(word) {
var nodeArray = []
for (var x = 0, length = word.length; x < length; x++) {
nodeArray.push(word.charCodeAt(x));
}
return nodeArray;
};
Tree.prototype.transverseNodes = function(word, bool) {
// make all of the letters lowercase to create uniformity
var nodes = this.stringToNodes(word.toLowerCase());
// console.log(nodes);
// start with parent/root tree
var currentTreeNode = this
// transverse checking if node has been added, if not add it
// if it was already added and it terminates a word set it "isword" property to true
for (var i = 0, length = nodes.length; i < length; i++) {
var node = nodes[i];
// If the current tree node is defined so not overwrite it
if (currentTreeNode.node[node] === null) {
if (!bool) {
// if bool is undefined of false, then this is a search
return false;
}
// create a node
currentTreeNode.node[node] = new Tree();
currentTreeNode.node[node].character = String.fromCharCode(node);
}
// check if the node is the last character of the word
if ((nodes.length - 1) === i) {
// console.log(nodes.length - 1, i)
if (!bool) {
// if bool is undefined of false, then this is a search
return true;
}
currentTreeNode.node[node].isword = true;
}
// get into the nested node
currentTreeNode = currentTreeNode.node[node];
};
return this;
};
var tree = new Tree()
// Create the nodes
tree.addNode("cat");
tree.addNode("camel");
tree.addNode("condom");
tree.addNode("catastrophe");
tree.addNode("grandma");
tree.addNode("lamboghini");
// Search the nodes
console.log(tree.searchForNodes("cat")); // true
console.log(tree.searchForNodes("catapult")); // false
console.log(tree.searchForNodes("catastrophe")); // true
console.log(tree.searchForNodes("mama")); // false
console.log(tree.searchForNodes("lamboghini")); // true
// retrieving all node
// console.log(tree.retrieveAllNodes());
This proposal features an iterative and recursive approach for getting the words in the tree.
'use strict';
// As illustrated in:
// http://programminggeeks.com/c-code-for-radix-tree-or-trie/
// Make a class of the Tree so that you can define methods all nodes of the tree
// which are actually Trees in structure inherit the functions
function Tree() {
this.character = undefined;
// if this node is the end of a complete word
// this was we can differentiate "sell" and "sells" if both are searched for
this.isword = false;
// How to nest the nodes, thus creating a tree structure
this.node = {}; // [new Tree(), new Tree(), new Tree()];
// abcdefghijklmnopqrstuvwxyz
var start = 97,
end = start + 25;
function constructor(that) {
for (var x = start; x <= end; x++) {
// for now they are all unsigned objects
that.node[x] = null // new Tree()
}
return that;
}
constructor(this);
return this;
}
Tree.prototype.addNode = function (word) {
return this.transverseNodes(word, true);
};
Tree.prototype.searchForNodes = function (word) {
return this.transverseNodes(word, false);
};
Tree.prototype.stringToNodes = function (word) {
var nodeArray = []
for (var x = 0, length = word.length; x < length; x++) {
nodeArray.push(word.charCodeAt(x));
}
return nodeArray;
};
Tree.prototype.transverseNodes = function (word, bool) {
// make all of the letters lowercase to create uniformity
var nodes = this.stringToNodes(word.toLowerCase());
// console.log(nodes);
// start with parent/root tree
var currentTreeNode = this
// transverse checking if node has been added, if not add it
// if it was already added and it terminates a word set it "isword" property to true
for (var i = 0, length = nodes.length; i < length; i++) {
var node = nodes[i];
// If the current tree node is defined so not overwrite it
if (currentTreeNode.node[node] === null) {
if (!bool) {
// if bool is undefined of false, then this is a search
return false;
}
// create a node
currentTreeNode.node[node] = new Tree();
currentTreeNode.node[node].character = String.fromCharCode(node);
}
// check if the node is the last character of the word
if ((nodes.length - 1) === i) {
// console.log(nodes.length - 1, i)
if (!bool) {
// if bool is undefined of false, then this is a search
return true;
}
currentTreeNode.node[node].isword = true;
}
// get into the nested node
currentTreeNode = currentTreeNode.node[node];
};
return this;
};
Tree.prototype.retrieveAllNodes = function () {
// function for traversing over object, takes the object and an empty string for
// the appearing words, acts as closure for the object
function iterObject(o, r) {
// how i like to start functions with return (...)
// returns basically the up coming word.
// reason for reduce, this provides a return value, with the letters
// of the path
return Object.keys(o).reduce(function (r, key) {
// check if the key property has a truthy value (remember the default
// null values)
if (o[key]) {
// if so, check the property isword
if (o[key].isword) {
// if its truty here, we have a hit, a word is found
wordList.push(r + o[key].character);
};
// check for children
if (o[key].node) {
// if node exist, go on with a new iteration and a new word
// extension
iterObject(o[key].node, r + o[key].character);
}
}
// return the inevitable word stem
return r;
}, r);
}
var wordList = [];
iterObject(this.node, '');
return wordList;
}
var tree = new Tree();
// Create the nodes
tree.addNode("cat");
tree.addNode("camel");
tree.addNode("condom");
tree.addNode("catastrophe");
tree.addNode("grandma");
tree.addNode("lamboghini");
// Search the nodes
console.log(tree.searchForNodes("cat")); // true
console.log(tree.searchForNodes("catapult")); // false
console.log(tree.searchForNodes("catastrophe")); // true
console.log(tree.searchForNodes("mama")); // false
console.log(tree.searchForNodes("lamboghini")); // true
// retrieving all words
console.log(JSON.stringify(tree.retrieveAllNodes(), 0, 4));
// retrieving whole tree
console.log(JSON.stringify(tree, 0, 4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Bonus: Below is a version with very small overhead.
'use strict';
function Tree() {
return this;
}
Tree.prototype.addNode = function (word) {
this.stringToNodes(word).reduce(function (node, character, i, a) {
if (!node[character]) {
node[character] = {};
}
if (i === a.length - 1) {
node[character].isword = true;
}
return node[character];
}, this);
return this;
};
Tree.prototype.searchForNodes = function (word) {
function iterObject(o, r) {
return Object.keys(o).reduce(function (r, key) {
if (key === 'isword' && r === word) {
found = true;
}
typeof o[key] === 'object' && iterObject(o[key], r + key);
return r;
}, r);
}
var found = false;
iterObject(this, '');
return found;
};
Tree.prototype.stringToNodes = function (word) {
return word.toLowerCase().split('');
};
Tree.prototype.retrieveAllNodes = function () {
function iterObject(o, r) {
return Object.keys(o).reduce(function (r, key) {
key === 'isword' && wordList.push(r);
typeof o[key] === 'object' && iterObject(o[key], r + key);
return r;
}, r);
}
var wordList = [];
iterObject(this, '');
return wordList;
}
var tree = new Tree();
// Create the nodes
tree.addNode("cat");
tree.addNode("camel");
tree.addNode("condom");
tree.addNode("catastrophe");
tree.addNode("grandma");
tree.addNode("lamboghini");
// Search the nodes
console.log(tree.searchForNodes("cat")); // true
console.log(tree.searchForNodes("catapult")); // false
console.log(tree.searchForNodes("catastrophe")); // true
console.log(tree.searchForNodes("mama")); // false
console.log(tree.searchForNodes("lamboghini")); // true
// retrieving all words
console.log(JSON.stringify(tree.retrieveAllNodes(), 0, 4));
// retrieving whole tree
console.log(JSON.stringify(tree, 0, 4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I'm not sure if you're doing that for studying, but if not, I suggest you to not reinvent the wheel, and try some library that already exists for that purpose, e.g. Javid Jamae's RadixTreeJS.
I should suppose to flatten a object, to do this I use this function:
var flatter = function(ob){
var f = {};
for(var i in ob) {
if(typeof ob[i] == 'object') {
var newOb = flatter(ob[i]);
for(var x in newOb) {
f[i+'.'+x] = newOb[x];
}
}else{
f[i] = ob[i];
}
}
return f;
}
works fine. I am getting proper result to applying this object:
var ob = {
"address" : {
"details" : {
"first" : "siva",
"last" : "sankara",
"mam":["mam1","mam2"]
}
}
};
the result is :
reslut : Object {address.details.first: "siva", address.details.last: "sankara", address.details.mam.0: "mam1", address.details.mam.1: "mam2"}
But I am not able to understand the result how i am getting. I understand that, this is oriented with recursion and closure scope - But seaching google I am not get any clear tutorial or article.
Any one help me to understand this my step by step please?
Here is the live demo
Thanks In advance!
function flatter(ob){
'use strict';
var f = {}, //return this
key;
for(key in ob) { //for each key
if (ob.hasOwnProperty(key)) {
if(typeof ob[key] === 'object') { //if value is object
//flatten this object again. Assign result to newOb
var newOb = flatter(ob[key]);
for(var x in newOb) {
f[key + '.' + x] = newOb[x];
}
} else {
f[key] = ob[key];
}
}
}
return f;
}
you can translate this code in something like that
function flatter(ob){
'use strict';
var f = {}, //return this object
key;
for(key in ob) { //for each key
if (ob.hasOwnProperty(key)) {
if(typeof ob[key] === 'object') { //if value is object
var newOb = (function (ob) {
'use strict';
var f = {}, //return this object
key;
for(key in ob) { //for each key
if (ob.hasOwnProperty(key)) {
if(typeof ob[key] === 'object') { //if value is object
var newOb = flatter(ob[key]);
for(var x in newOb) {
f[key + '.' + x] = newOb[x];
}
} else {
f[key] = ob[key];
}
}
}
return f;
}(ob[key]));
for(var x in newOb) {
f[key + '.' + x] = newOb[x];
}
} else {
f[key] = ob[key];
}
}
}
return f;
}
main idea is that every function call can be substituted by body of this function.
Object itself is a recursive structure, because can content objects. If given
{
id: 12345,
name: 'John',
friends: [12346, 75645, 96768]
}
recursion is not needed. Object doesn't contain any objects, so it could be straigtened without additional function call (by the way it is flat). If given
{
id: 12345,
name: {
first: 'John',
last: 'Doe'
},
friends: [12346, 75645, 96768]
}
then object contains object as field. So you can use function flatter where function call is substituted with body of function. If given
{
id: 12345,
name: {
first: 'Helen',
last: {
beforeMarriage: 'Dobsky',
afterMarriage: 'Bobsky'
}
},
friends: [12346, 75645, 96768]
}
then one can't do without 3 function calls. So you can copy body of function three times. But, object can have [infinitely] very deep structure. So number of nested bodies of function is unknown. So, instead of nesting body of function into function recursive call is used.
Recursive function should have at least one exit point to avoid infinite recursion
return f;
in our case. This exit point can be reached because number of fields in object is finite. This is not the only way to solve task. As object looks like tree (a kind of) recursion could be substituted with stack, which keeps complex fields and after processing simple fields return back to stack of objects and treat them in a loop.
Stack implementation. Not beautiful, but works)
function iflatter(input) {
'use strict';
var f = {}, //return this object
key,
stack = [],
ob,
prefix,
name;
stack.push(["", input]);
while (stack.length != 0) {
[prefix, ob] = stack.pop();
for(key in ob) { //for each key
if (ob.hasOwnProperty(key)) {
if (prefix !== "") {
name = prefix + "." + key;
} else {
name = key;
}
if(typeof ob[key] === 'object') {
stack.push([name, ob[key]]);
} else {
f[name] = ob[key];
}
}
}
}
return f;
}
You are passing an Object to flatter(). When the Object has a property that has a value that is an Object itself, it passes that Object to flatter() again, or recursively. See if(typeof ob[i] == 'object')? That means that if ob has property i and its value (gotten as ob[i]) is an Object. Note var flatter = function(){} is equivalent to function flatter(){}.
i have this json structure and I made it into an array. I was trying to remove the entry, but this code failed on me: Remove item from array if it exists in a 'disallowed words' array
var historyList = []; // assuming this already has the array filled
function add() {
var newHistory = {
ID: randomString(),
Name: $('#txtVaccineName').val(),
DoseDate: doseDate,
ResultDate: resultDate,
Notes: $('#txtResultNotes').val()
};
historyList.push(newHistory);
};
function removeEntry(value) {
historyList.remove('ID', value);
};
Array.prototype.remove = function(name, value) {
array = this;
var rest = $.grep(this, function(item) {
return (item[name] != value);
});
array.length = rest.length;
$.each(rest, function(n, obj) {
array[n] = obj;
});
};
You could use a property filter to match the item in your history list. Below is the sample quick code to do so, I've modified your history list a bit.
A quick test in FF, shows that it works!
var historyList = []; // assuming this already has the array filled
function addToHistory(name, notes) {
var newHistory = {
ID: new Date().getTime(),
Name: name,
DoseDate: "Somedate",
ResultDate: "SomeResultDate",
Notes: notes,
toString: function() {return this.Name;}
};
historyList.push(newHistory);
};
var Util = {};
/**
* Gets the index if first matching item in an array, whose
* property (specified by name) has the value specified by "value"
* #return index of first matching item or false otherwise
*/
Util.arrayIndexOf = function(arr, filter) {
for(var i = 0, len = arr.length; i < len; i++) {
if(filter(arr[i])) {
return i;
}
}
return -1;
};
/**
* Matches if the property specified by pName in the given item,
* has a value specified by pValue
* #return true if there is a match, false otherwise
*/
var propertyMatchFilter = function(pName, pValue) {
return function(item) {
if(item[pName] === pValue) {
return true;
}
return false;
}
}
/**
* Remove from history any item whose property pName has a value
* pValue
*/
var removeHistory = function(pName, pValue) {
var nameFilter = propertyMatchFilter(pName, pValue);
var idx = Util.arrayIndexOf(historyList, nameFilter);
if(idx != -1) {
historyList.splice(idx, 1);
}
};
// ---------------------- Tests -----------------------------------
addToHistory("history1", "Note of history1");
addToHistory("history2", "Note of history2");
addToHistory("history3", "Note of history3");
addToHistory("history4", "Note of history4");
alert(historyList); // history1,history2,history3,history4
removeHistory("Name", "history1");
alert(historyList); // history2,history3,history4
removeHistory("Notes", "Note of history3");
alert(historyList); // history2,history4
The entire Array.prototype.remove function can be inlined as follows:
function removeEntry(value) {
historyList = $.grep(historyList, function(item) {
return (item.ID !== value);
});
}
You can, of course, create a function to wrap $.grep or the predicate as you wish. (And if you do, you probably don't want to modify Array.prototype; prefer modifying historyList itself (using Array.prototype.splice) or creating a (likely static) function elsewhere.)
Also, this problem does not relate to the SO question you mention in your question, as far as I can tell.