Is it possible to add to a multidimensional array of unknown size without using a google sheets(spreadsheet) to hold the data? Looking everywhere and can't find an example for a 3 dimensional array.
Here is what I want to do:
var aDirTree=[];
aDirTree[0][0][0]="myName1";
aDirTree[0][0][1]="myURL1";
aDirTree[1][0][0]="myName2";
aDirTree[1][0][1]="myURL2";
//Notice we are skipping elements
aDirTree[2][5][0]="myName3";
aDirTree[2][5][1]="myURL3";
Where values that are skipped are null? I'm guessing it might be some sort of push method.
In the lazier version, array can be used as a key (but it's converted to string) :
var o = {}
o[[1,2,3]]='a'
o['4,5,6']='b'
console.log(o) // { "1,2,3": "a", "4,5,6": "b" }
console.log(o[[0,0,0]]) // undefined
Proxy(not available in IE)
can be another alternative, but it will create a lot of extra values:
var handler = { get: (a, i) => i in a ? a[i] : a[i] = new Proxy([], handler) }
var a = new Proxy([], handler)
a[1][2][3]='a'
a[4][5][6]='b'
console.log(a) // [[],[[],[],[[],[],[],"a"]],[],[],[[],[],[],[],[],[[],[],[],[],[],[],"b"]]]
console.log(a[0][0][0]) // []
And finally, the "real" answer:
function set(a, x, y, z, v) { ((a = a[x] || (a[x] = []))[y] || (a[y] = []))[z] = v }
function get(a, x, y, z, v) { return (a = a[x]) && (a = a[y]) && z in a ? a[z] : v }
var a = []
set(a,1,2,3,'a')
set(a,4,5,6,'b')
console.log( get(a,0,0,0) ) // undefined
console.log( get(a,0,0,0,'default') ) // "default"
console.log( a ) // [,[,,[,,,"a"]],,,[,,,,,[,,,,,,"b"]]]
Bonus: combination of all 3, but not very efficient, because the keys are converted to strings:
var a = [], p = new Proxy(a, { set: (a, k, v) =>
([x,y,z] = k.split(','), ((a = a[x] || (a[x] = []))[y] || (a[y] = []))[z] = v) })
p[[1,2,3]] = 'a'
p[[4,5,6]] = 'b'
console.log( a[[0,0,0]] ) // undefined
console.log( a ) // [,[,,[,,,"a"]],,,[,,,,,[,,,,,,"b"]]]
function writeToTree(tree, first, second, third, value)
{
tree[first] || (tree[first] = []);
tree[first][second] || (tree[first][second] = []);
tree[first][second][third] || (tree[first][second][third] = []);
tree[first][second][third] = value;
}
var aDirTree = [];
writeToTree(aDirTree, 1, 55, 3, "someValue");
Or recursively, giving you arbitrary depth:
function writeToTree(tree, position, value)
{
var insertAt = position.shift();
tree[insertAt] || (tree[insertAt] = []);
if (position.length === 0)
{
tree[insertAt] = value;
return;
}
writeToTree(tree[insertAt], position, value);
}
var aDirTree = [];
writeToTree(aDirTree, [1, 55, 3], "someValue");
console.log(aDirTree);
Related
I hope someone can help me with this Javascript.
I have an Object called "Settings" and I would like to write a function that adds new settings to that object.
The new setting's name and value are provided as strings. The string giving the setting's name is then split by the underscores into an array. The new setting should get added to the existing "Settings" object by creating new nested objects with the names given by each part of the array, except the last part which should be a string giving the setting's value. I should then be able to refer to the setting and e.g. alert its value. I can do this in a static way like this...
var Settings = {};
var newSettingName = "Modules_Video_Plugin";
var newSettingValue = "JWPlayer";
var newSettingNameArray = newSettingName.split("_");
Settings[newSettingNameArray[0]] = {};
Settings[newSettingNameArray[0]][newSettingNameArray[1]] = {};
Settings[newSettingNameArray[0]][newSettingNameArray[1]][newSettingNameArray[2]] = newSettingValue;
alert(Settings.Modules.Mediaplayers.Video.Plugin);
... the part that creates the nested objects is doing this ...
Settings["Modules"] = {};
Settings["Modules"]["Video"] = {};
Settings["Modules"]["Video"]["Plugin"] = "JWPlayer";
However, as the number of parts that make up the setting name can vary, e.g. a newSettingName could be "Modules_Floorplan_Image_Src", I'd like to do this dynamically using a function such as...
createSetting (newSettingNameArray, newSettingValue);
function createSetting(setting, value) {
// code to create new setting goes here
}
Can anyone help me work out how to do this dynamically?
I presume there has to be a for...loop in there to itterate through the array, but I haven't been able to work out a way to create the nested objects.
If you've got this far thanks very much for taking the time to read even if you can't help.
Put in a function, short and fast (no recursion).
var createNestedObject = function( base, names ) {
for( var i = 0; i < names.length; i++ ) {
base = base[ names[i] ] = base[ names[i] ] || {};
}
};
// Usage:
createNestedObject( window, ["shapes", "triangle", "points"] );
// Now window.shapes.triangle.points is an empty object, ready to be used.
It skips already existing parts of the hierarchy. Useful if you are not sure whether the hierarchy was already created.
Or:
A fancier version where you can directly assign the value to the last object in the hierarchy, and you can chain function calls because it returns the last object.
// Function: createNestedObject( base, names[, value] )
// base: the object on which to create the hierarchy
// names: an array of strings contaning the names of the objects
// value (optional): if given, will be the last object in the hierarchy
// Returns: the last object in the hierarchy
var createNestedObject = function( base, names, value ) {
// If a value is given, remove the last name and keep it for later:
var lastName = arguments.length === 3 ? names.pop() : false;
// Walk the hierarchy, creating new objects where needed.
// If the lastName was removed, then the last object is not set yet:
for( var i = 0; i < names.length; i++ ) {
base = base[ names[i] ] = base[ names[i] ] || {};
}
// If a value was given, set it to the last name:
if( lastName ) base = base[ lastName ] = value;
// Return the last object in the hierarchy:
return base;
};
// Usages:
createNestedObject( window, ["shapes", "circle"] );
// Now window.shapes.circle is an empty object, ready to be used.
var obj = {}; // Works with any object other that window too
createNestedObject( obj, ["shapes", "rectangle", "width"], 300 );
// Now we have: obj.shapes.rectangle.width === 300
createNestedObject( obj, "shapes.rectangle.height".split('.'), 400 );
// Now we have: obj.shapes.rectangle.height === 400
Note: if your hierarchy needs to be built from values other that standard objects (ie. not {}), see also TimDog's answer below.
Edit: uses regular loops instead of for...in loops. It's safer in cases where a library modifies the Array prototype.
function assign(obj, keyPath, value) {
lastKeyIndex = keyPath.length-1;
for (var i = 0; i < lastKeyIndex; ++ i) {
key = keyPath[i];
if (!(key in obj)){
obj[key] = {}
}
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
Usage:
var settings = {};
assign(settings, ['Modules', 'Video', 'Plugin'], 'JWPlayer');
My ES2015 solution. Keeps existing values.
const set = (obj, path, val) => {
const keys = path.split('.');
const lastKey = keys.pop();
const lastObj = keys.reduce((obj, key) =>
obj[key] = obj[key] || {},
obj);
lastObj[lastKey] = val;
};
Example:
const obj = {'a': {'prop': {'that': 'exists'}}};
set(obj, 'a.very.deep.prop', 'value');
console.log(JSON.stringify(obj));
// {"a":{"prop":{"that":"exists"},"very":{"deep":{"prop":"value"}}}}
Using ES6 is shorten. Set your path into an array.
first, you have to reverse the array, to start filling the object.
let obj = ['a','b','c'] // {a:{b:{c:{}}}
obj.reverse();
const nestedObject = obj.reduce((prev, current) => (
{[current]:{...prev}}
), {});
Another recursive solution:
var nest = function(obj, keys, v) {
if (keys.length === 1) {
obj[keys[0]] = v;
} else {
var key = keys.shift();
obj[key] = nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v);
}
return obj;
};
Example usage:
var dog = {bark: {sound: 'bark!'}};
nest(dog, ['bark', 'loudness'], 66);
nest(dog, ['woff', 'sound'], 'woff!');
console.log(dog); // {bark: {loudness: 66, sound: "bark!"}, woff: {sound: "woff!"}}
I love this ES6 immutable way to set certain value on nested field:
const setValueToField = (fields, value) => {
const reducer = (acc, item, index, arr) => ({ [item]: index + 1 < arr.length ? acc : value });
return fields.reduceRight(reducer, {});
};
And then use it with creating your target object.
const targetObject = setValueToField(['one', 'two', 'three'], 'nice');
console.log(targetObject); // Output: { one: { two: { three: 'nice' } } }
Lodash has a _.set method to achieve this
let obj = {}
_.set(obj, ['a', 'b', 'c', 'd'], 'e')
or
_.set(obj, 'a.b.c.d', 'e')
// which generate the following object
{
"a": {
"b": {
"c": {
"d": "e"
}
}
}
}
Here is a simple tweak to jlgrall's answer that allows setting distinct values on each element in the nested hierarchy:
var createNestedObject = function( base, names, values ) {
for( var i in names ) base = base[ names[i] ] = base[ names[i] ] || (values[i] || {});
};
Hope it helps.
Here is a functional solution to dynamically create nested objects.
const nest = (path, obj) => {
const reversedPath = path.split('.').reverse();
const iter = ([head, ...tail], obj) => {
if (!head) {
return obj;
}
const newObj = {[head]: {...obj}};
return iter(tail, newObj);
}
return iter(reversedPath, obj);
}
Example:
const data = {prop: 'someData'};
const path = 'a.deep.path';
const result = nest(path, data);
console.log(JSON.stringify(result));
// {"a":{"deep":{"path":{"prop":"someData"}}}}
Inspired by ImmutableJS setIn method which will never mutate the original. This works with mixed array and object nested values.
function setIn(obj = {}, [prop, ...rest], value) {
const newObj = Array.isArray(obj) ? [...obj] : {...obj};
newObj[prop] = rest.length ? setIn(obj[prop], rest, value) : value;
return newObj;
}
var obj = {
a: {
b: {
c: [
{d: 5}
]
}
}
};
const newObj = setIn(obj, ["a", "b", "c", 0, "x"], "new");
//obj === {a: {b: {c: [{d: 5}]}}}
//newObj === {a: {b: {c: [{d: 5, x: "new"}]}}}
Appreciate that this question is mega old! But after coming across a need to do something like this in node, I made a module and published it to npm.
Nestob
var nestob = require('nestob');
//Create a new nestable object - instead of the standard js object ({})
var newNested = new nestob.Nestable();
//Set nested object properties without having to create the objects first!
newNested.setNested('biscuits.oblong.marmaduke', 'cheese');
newNested.setNested(['orange', 'tartan', 'pipedream'], { poppers: 'astray', numbers: [123,456,789]});
console.log(newNested, newNested.orange.tartan.pipedream);
//{ biscuits: { oblong: { marmaduke: 'cheese' } },
orange: { tartan: { pipedream: [Object] } } } { poppers: 'astray', numbers: [ 123, 456, 789 ] }
//Get nested object properties without having to worry about whether the objects exist
//Pass in a default value to be returned if desired
console.log(newNested.getNested('generic.yoghurt.asguard', 'autodrome'));
//autodrome
//You can also pass in an array containing the object keys
console.log(newNested.getNested(['chosp', 'umbridge', 'dollar'], 'symbols'));
//symbols
//You can also use nestob to modify objects not created using nestob
var normalObj = {};
nestob.setNested(normalObj, 'running.out.of', 'words');
console.log(normalObj);
//{ running: { out: { of: 'words' } } }
console.log(nestob.getNested(normalObj, 'random.things', 'indigo'));
//indigo
console.log(nestob.getNested(normalObj, 'improbable.apricots'));
//false
Inside your loop you can use lodash.set and will create the path for you:
...
const set = require('lodash.set');
const p = {};
const [type, lang, name] = f.split('.');
set(p, [lang, type, name], '');
console.log(p);
// { lang: { 'type': { 'name': '' }}}
try using recursive function:
function createSetting(setting, value, index) {
if (typeof index !== 'number') {
index = 0;
}
if (index+1 == setting.length ) {
settings[setting[index]] = value;
}
else {
settings[setting[index]] = {};
createSetting(setting, value, ++index);
}
}
I think, this is shorter:
Settings = {};
newSettingName = "Modules_Floorplan_Image_Src";
newSettingValue = "JWPlayer";
newSettingNameArray = newSettingName.split("_");
a = Settings;
for (var i = 0 in newSettingNameArray) {
var x = newSettingNameArray[i];
a[x] = i == newSettingNameArray.length-1 ? newSettingValue : {};
a = a[x];
}
I found #jlgrall's answer was great but after simplifying it, it didn't work in Chrome. Here's my fixed should anyone want a lite version:
var callback = 'fn.item1.item2.callbackfunction',
cb = callback.split('.'),
baseObj = window;
function createNestedObject(base, items){
$.each(items, function(i, v){
base = base[v] = (base[v] || {});
});
}
callbackFunction = createNestedObject(baseObj, cb);
console.log(callbackFunction);
I hope this is useful and relevant. Sorry, I've just smashed this example out...
You can define your own Object methods; also I'm using underscore for brevity:
var _ = require('underscore');
// a fast get method for object, by specifying an address with depth
Object.prototype.pick = function(addr) {
if (!_.isArray(addr)) return this[addr]; // if isn't array, just get normally
var tmpo = this;
while (i = addr.shift())
tmpo = tmpo[i];
return tmpo;
};
// a fast set method for object, put value at obj[addr]
Object.prototype.put = function(addr, val) {
if (!_.isArray(addr)) this[addr] = val; // if isn't array, just set normally
this.pick(_.initial(addr))[_.last(addr)] = val;
};
Sample usage:
var obj = {
'foo': {
'bar': 0 }}
obj.pick('foo'); // returns { bar: 0 }
obj.pick(['foo','bar']); // returns 0
obj.put(['foo', 'bar'], -1) // obj becomes {'foo': {'bar': -1}}
A snippet for those who need to create a nested objects with support of array keys to set a value to the end of path. Path is the string like: modal.product.action.review.2.write.survey.data. Based on jlgrall version.
var updateStateQuery = function(state, path, value) {
var names = path.split('.');
for (var i = 0, len = names.length; i < len; i++) {
if (i == (len - 1)) {
state = state[names[i]] = state[names[i]] || value;
}
else if (parseInt(names[i+1]) >= 0) {
state = state[names[i]] = state[names[i]] || [];
}
else {
state = state[names[i]] = state[names[i]] || {};
}
}
};
Set Nested Data:
function setNestedData(root, path, value) {
var paths = path.split('.');
var last_index = paths.length - 1;
paths.forEach(function(key, index) {
if (!(key in root)) root[key] = {};
if (index==last_index) root[key] = value;
root = root[key];
});
return root;
}
var obj = {'existing': 'value'};
setNestedData(obj, 'animal.fish.pet', 'derp');
setNestedData(obj, 'animal.cat.pet', 'musubi');
console.log(JSON.stringify(obj));
// {"existing":"value","animal":{"fish":{"pet":"derp"},"cat":{"pet":"musubi"}}}
Get Nested Data:
function getNestedData(obj, path) {
var index = function(obj, i) { return obj && obj[i]; };
return path.split('.').reduce(index, obj);
}
getNestedData(obj, 'animal.cat.pet')
// "musubi"
getNestedData(obj, 'animal.dog.pet')
// undefined
Try this: https://github.com/silkyland/object-to-formdata
var obj2fd = require('obj2fd/es5').default
var fd = obj2fd({
a:1,
b:[
{c: 3},
{d: 4}
]
})
Result :
fd = [
a => 1,
b => [
c => 3,
d => 4
]
]
Here is a decomposition to several useful functions, that each preserve existing data. Does not handle arrays.
setDeep: Answers question. Non-destructive to other data in the object.
setDefaultDeep: Same, but only sets if not already set.
setDefault: Sets a key if not already set. Same as Python's setdefault.
setStructure: Helper function that builds the path.
// Create a nested structure of objects along path within obj. Only overwrites the final value.
let setDeep = (obj, path, value) =>
setStructure(obj, path.slice(0, -1))[path[path.length - 1]] = value
// Create a nested structure of objects along path within obj. Does not overwrite any value.
let setDefaultDeep = (obj, path, value) =>
setDefault(setStructure(obj, path.slice(0, -1)), path[path.length - 1], value)
// Set obj[key] to value if key is not in object, and return obj[key]
let setDefault = (obj, key, value) =>
obj[key] = key in obj ? obj[key] : value;
// Create a nested structure of objects along path within obj. Does not overwrite any value.
let setStructure = (obj, path) =>
path.reduce((obj, segment) => setDefault(obj, segment, {}), obj);
// EXAMPLES
let temp = {};
// returns the set value, similar to assignment
console.log('temp.a.b.c.d:',
setDeep(temp, ['a', 'b', 'c', 'd'], 'one'))
// not destructive to 'one'
setDeep(temp, ['a', 'b', 'z'], 'two')
// does not overwrite, returns previously set value
console.log('temp.a.b.z: ',
setDefaultDeep(temp, ['a', 'b', 'z'], 'unused'))
// creates new, returns current value
console.log('temp["a.1"]: ',
setDefault(temp, 'a.1', 'three'))
// can also be used as a getter
console.log("temp.x.y.z: ",
setStructure(temp, ['x', 'y', 'z']))
console.log("final object:", temp)
I'm not sure why anyone would want string paths:
They are ambiguous for keys with periods
You have to build the strings in the first place
Since I started with something from this page, I wanted to contribute back
Other examples overwrote the final node even if it was set, and that wasn't what I wanted.
Also, if returnObj is set to true, it returns the base object. By default, falsy, it returns the deepest node.
function param(obj, path, value, returnObj) {
if (typeof path == 'string') path = path.split(".");
var child = obj;
path.forEach((key, i) => {
if (!(key in child)) {
child[key] = (i < path.length-1) ? {} : value || {};
}
child = child[key];
});
return returnObj ? obj : child;
}
var x = {};
var xOut = param(x, "y.z", "setting")
console.log(xOut);
xOut = param(x, "y.z", "overwrite") // won't set
console.log(xOut);
xOut = param(x, "y.a", "setting2")
console.log(xOut);
xOut = param(x, "y.a", "setting2", true) // get object rather than deepest node.
console.log(xOut);
You can also do something where numeric keys are placed in arrays (if they don't already exist). Note that numeric keys won't convert to arrays for the first element of the path, since that's set by the type of your base-object.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function param(obj, path, value, returnObj) {
if (typeof path == 'string') path = path.split(".");
var child = obj;
path.forEach((key, i) => {
var nextKey = path[i+1];
if (!(key in child)) {
child[key] = (nextKey == undefined && value != undefined
? value
: isNumber(nextKey)
? []
: {});
}
child = child[key];
});
return returnObj ? obj : child;
}
var x = {};
var xOut = param(x, "y.z", "setting")
console.log(xOut);
xOut = param(x, "y.z", "overwrite") // won't set
console.log(xOut);
xOut = param(x, "y.a", "setting2")
console.log(xOut);
xOut = param(x, "y.a", "setting2", true) // get object rather than deepest node.
xOut = param(x, "1.0.2.a", "setting")
xOut = param(x, "1.0.1.a", "try to override") // won't set
xOut = param(x, "1.0.5.a", "new-setting", true) // get object rather than deepest node.
console.log(xOut);
Naturally, when the numeric keys are greater than 0, you might see some undefined gaps.
Practical uses of this might be
function AddNote(book, page, line) {
// assume a global global notes collection
var myNotes = param(allNotes, [book, page, line], []);
myNotes.push('This was a great twist!')
return myNotes;
}
var allNotes = {}
var youthfulHopes = AddNote('A Game of Thrones', 4, 2, "I'm already hooked, at least I won't have to wait long for the books to come out!");
console.log(allNotes)
// {"A Game of Thrones": [undefined, undefined, undefined, undefined, [undefined, undefined, ["I'm already hooked, at least I won't have to wait long for the books to come out!"]]]}
console.log(youthfulHopes)
// ["I'm already hooked, at least I won't have to wait long for the books to come out!"]
function initPath(obj, path) {
path.split('.').reduce((o, key) => (
Object.assign(o, {[key]: Object(o[key])}),
o[key]
), obj);
return obj;
}
Usage
const obj = { a: { b: 'value1' } };
initPath(obj, 'a.c.d').a.c.d='value2';
/*
{
"a": {
"b": "value1",
"c": {
"d": "value2"
}
}
}
*/
simple answer. on es6, im using this
const assign = (obj, path, value) => {
let keyPath = path.split('.')
let lastKeyIndex = keyPath.length - 1
for (let i = 0; i < lastKeyIndex; ++i) {
let key = keyPath[i]
if (!(key in obj)) {
obj[key] = {}
}
obj = obj[key]
}
obj[keyPath[lastKeyIndex]] = value
}
example json
const obj = {
b: 'hello'
}
you can add new key
assign(obj, 'c.d.e', 'this value')
and you get like bellow
console.log(obj)
//response example
obj = {
b: 'hello',
c: {
d: {
e: 'this value'
}
}
}
function createObj(keys, value) {
let obj = {}
let schema = obj
keys = keys.split('.')
for (let i = 0; i < keys.length - 1; i++) {
schema[keys[i]] = {}
schema = schema[keys[i]]
}
schema[keys.pop()] = value
return obj
}
let keys = 'value1.value2.value3'
let value = 'Hello'
let obj = createObj(keys, value)
Eval is probably overkill but the result is simple to visualize, with no nested loops or recursion.
function buildDir(obj, path){
var paths = path.split('_');
var final = paths.pop();
for (let i = 1; i <= paths.length; i++) {
var key = "obj['" + paths.slice(0, i).join("']['") + "']"
console.log(key)
eval(`${key} = {}`)
}
eval(`${key} = '${final}'`)
return obj
}
var newSettingName = "Modules_Video_Plugin_JWPlayer";
var Settings = buildDir( {}, newSettingName );
Basically you are progressively writing a string "obj['one']= {}", "obj['one']['two']"= {} and evaling it;
I need to treat array values as props of object. For example:
let arr = ['masa_icerik', 'urunler', 0, 'urun_adet'];
let obj = {
"_id": "5c13bd566704aa5e372dddcf",
"masa_id": 3,
"masa_numara": 3,
"masa_magaza": 1,
"masa_icon": "kola",
"masa_adi": "salon 3",
"masa_durum": 1,
"masa_icerik": {
"adisyon": "J1554745811908",
"urunler": [{
"urun_adet": 14,
"urun_fiyat": 3,
"urun_id": "5c16686b93d7b79ae6367864",
"urun_odenen": 0
}, {
"urun_adet": 1,
"urun_fiyat": 5,
"urun_id": "5c16686b93d7b79ae6367865",
"urun_odenen": 0
}]
},
"masa_acilis": "2019-04-08T17:50:12.052Z",
"masa_acan": "5c1eda01d1f4773110dd6ada"
};
I have an array and an object like above and I want to do something like this:
let res;
arr.forEach(elem => {
res = obj[elem];
});
and after that I need to get something like :
obj['masa_icerik']['urunler'][0]['urun_adet']
The number of the values is dynamic from server. Thats why i need something like this. Is there any way to do that? I need to change that property and return the changed obj.
You can use forEach loop to loop thru the array and store it to a temp variable. If all elements exist, it will change the value.
let arr = ['a', 'b', 'c'];
let obj = {'a':{'b':{'c':1}}};
let newValue = "NEW VALUE";
let temp = obj;
arr.forEach((o, i) => {
if (i < arr.length - 1) temp = temp[o] || null;
else if (temp !== null && typeof temp === "object" ) temp[o] = newValue;
});
console.log(obj);
If there are multiple multiple object properties missing in the last part of the array.
let arr = ['a', 'b', 'c', 'd'];
let obj = {'a': {'b': {}}};
let newValue = "NEW VALUE";
let temp = obj;
arr.forEach((o, i) => {
if (i < arr.length - 1) {
if (!temp[o]) temp[o] = {[arr[i + 1]]: {}};
temp = temp[o];
} else if (temp !== null && typeof temp === "object") temp[o] = newValue;
});
console.log(obj);
You can use references
Here idea is
Initialize val with object reference
Loop through array and keep setting new reference to val
let arr = ['a','b','c'];
let obj = {'a':{'b':{'c':1}}};
let getMeValue = (arr) => {
let val=obj;
arr.forEach(e => val = val && val[e] )
return val
}
console.log(getMeValue(arr))
console.log(getMeValue([1,2,3]))
UPDATE: I want to change values
let arr = ['a','b','c'];
let obj = {'a':{'b':{'c':1}}};
let getMeValue = (arr) => {
let val = obj
arr.forEach((e,i) => {
if(i === arr.length-1 && val){
val[e] = 5
}
else {
val = val && val[e]
}
})
return obj
}
console.log(getMeValue(arr))
I am not fully understanding where you are getting the new values from but I think this will get you on the right track.
let newObj = {};
arr.map(each => {
newObj[each] = "new value";
})
console.log(newObj);
I'm not sure about your requirment here, I guess you want the below:
let func = (arr, value)=>{
r = {};
r[arr[arr.length-1]] = value;
for(let i = arr.length-2; i>=0; i--){
obj = {};
obj[arr[i]] = r;
r = obj;
}
return r;
}
console.log(func(['a', 'b', 'c'], 1));
I've written a method to imitate the Null conditional operator / Elvis operator , including autocomplete and array support :
Say I have this object :
var o = { a: { b: { c:[{a:1},{a:2}] , s:"hi"} } };
I can access the second element in the array and fetch a :
if ( n(o, (k) => k.a.b.c[1].a) == 2 )
{
alert('Good'); //true
}
What I've done was to cause the expression to be sent as a function , which then I can parse as string :
function n<T>(o :T , action : (a:T)=>any):any {
let s = action.toString().toString().split('return')[1].split('}')[0].split(';')[0];
s = s.replace(/\[(\w+)\]/g, '.$1'); //for array access
s = s.replace(/^\./, ''); //remove first dot
var a = s.split('.');
for (var i = 1, n = a.length; i < n; ++i) { //i==0 is the k itself ,aand we dont need it
var k = a[i];
if ( o && o.hasOwnProperty(k)) {
o = o[k];
} else {
return null;
}
}
return o;
}
It does work as expected , but I have a small problem.
The signature of the method returns any :
function n<T>(o :T , action : (a:T)=>any) :any
^^^
Question:
Is there any option that the return value will more specific ( or even exact) as the prop I'm trying to access ?
So n(o, (k) => k.a.b.c[1].a) will be :number
and n(o, (k) => k.a.b.s) will be :string
Is it possible ? if not , is there a way to make return value to be more "typi" ?
Link for comment
You can just add an extra type parameter for the return value and let the compiler figure out that the type parameter is the return type of the expression:
var o = { a: { b: { c: [{ a: 1 }, { a: 2 }], s: "hi" } } };
function n<T, TValue>(o: T, action: (a: T) => TValue): TValue | null {
let s = action.toString().toString().split('return')[1].split('}')[0].split(';')[0];
s = s.replace(/\[(\w+)\]/g, '.$1'); //for array access
s = s.replace(/^\./, ''); //remove first dot
var a = s.split('.');
let result: any = o
for (var i = 1, n = a.length; i < n; ++i) { //i==0 is the k itself ,aand we dont need it
var k = a[i];
if ( result && result.hasOwnProperty(k)) {
result = result[k];
} else {
return null;
}
}
return result;
}
let nr = n(o, (k) => k.a.b.c[1].a) // is number | null
var str = n(o, (k) => k.a.b.s) // is string | null
Note The |null part is optional but makes sense in the context of your implementation.
So I have a series of arrays, each of which are 2500 long, and I need to serialize and store all them in very limited space.
Since I have many duplicates, I wanted to cut them down to something like below.
[0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0]
// to
[0x4,2,7,3x2,0x9]
I wrote a couple one-liners (utilising Lodash' _.repeat) to convert to and from this pattern, however converting to doesn't seem to work in most/all cases.
let serialized = array.toString().replace(/((?:(\d)+,?)((?:\2+,?){2,}))/g, (m, p1, p2) => p2 + 'x' + m.replace(/,/g, '').length);
let parsed = serialized.replace(/(\d+)x(\d+),?/g, (z, p1, p2) => _.repeat(p1 + ',', +p2)).split(',');
I don't know why it doesn't work. It may be due to some of the numbers in the array. Eye-balling, the largest one is 4294967295, however well over 90% is just 0.
What am I missing in my RegEx that's preventing it from working correctly? Is there a simpler way that I'm too blind to see?
I'm fairly confident with converting it back from the serialized state, just need a hand getting it to the state.
Straight forward and simple serialization:
let serialize = arr => {
const elements = [];
const counts = []
let last = undefined;
[0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0].forEach((el,i,arr)=>{
if (el!==last) {
elements.push(el);
counts.push(1);
} else {
counts[counts.length-1]++;
}
last = el;
})
return elements.map((a,i)=>counts[i]>1?`${a}x${counts[i]}`:a).join(",");
};
console.log(serialize([0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0]));
UPDATE
Pure functional serialize one:
let serialize = arr => arr
.reduce((memo, element, i) => {
if (element !== arr[i - 1]) {
memo.push({count: 1, element});
} else {
memo[memo.length - 1].count++;
}
return memo;
},[])
.map(({count, element}) => count > 1 ? `${count}x${element}` : element)
.join(",");
console.log(serialize([0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0]));
Pure functional deserialize:
const deserialize = str => str
.split(",")
.map(c => c.split("x").reverse())
.reduce((memo, [el, count = 1]) => memo.concat(Array(+count).fill(+el)), []);
console.log(deserialize("4x0,2,7,2x3,9x0"))
In order to avoid using .reverse() in this logic, I'd recommend to change serialization from 4x0 to 0x4
Try this
var arr = [0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0];
var finalArray = []; //array into which count of values will go
var currentValue = ""; //current value for comparison
var tmpArr = []; //temporary array to hold values
arr.forEach( function( val, index ){
if ( val != currentValue && currentValue !== "" )
{
finalArray.push( tmpArr.length + "x" + tmpArr[0] );
tmpArr = [];
}
tmpArr.push(val);
currentValue = val;
});
finalArray.push( tmpArr.length + "x" + tmpArr[0] );
console.log(finalArray);
Another version without temporary array
var arr = [0, 0, 0, 0, 2, 7, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var finalArray = []; //array into which count of values will go
var tmpCount = 0; //temporary variable to hold count
arr.forEach(function(val, index) {
if ( (val != arr[ index - 1 ] && index !== 0 ) )
{
finalArray.push(tmpCount + "x" + arr[ index - 1 ] );
tmpCount = 0;
}
tmpCount++;
if ( index == arr.length - 1 )
{
finalArray.push(tmpCount + "x" + arr[ index - 1 ] );
}
});
console.log(finalArray);
Do not use RegEx. Just use regular logic. I recommend array.reduce for this job.
const arr1 = [0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0]
const arr2 = ['0x4','2','7','3x2','0x9'];
const compact = arr => {
const info = arr.reduce((c, v) =>{
if(c.prevValue !== v){
c.order.push(v);
c.count[v] = 1;
c.prevCount = 1;
c.prevValue = v;
} else {
c.prevCount = c.prevCount + 1;
c.count[v] = c.count[v] + 1;
};
return c;
},{
prevValue: null,
prevCount: 0,
count: {},
order: []
});
return info.order.map(v => info.count[v] > 1 ? `${v}x${info.count[v]}` : `${v}`);
}
const expand = arr => {
return arr.reduce((c, v) => {
const split = v.split('x');
const value = +split[0];
const count = +split[1] || 1;
Array.prototype.push.apply(c, Array(count).fill(value));
return c;
}, []);
}
console.log(compact(arr1));
console.log(expand(arr2));
This is a typical reducing job. Here is your compress function done in just O(n) time..
var arr = [0,0,0,0,2,7,3,3,0,0,0,0,0,0,0,0,0],
compress = a => a.reduce((r,e,i,a) => e === a[i-1] ? (r[r.length-1][1]++,r) : (r.push([e,1]) ,r),[]);
console.log(JSON.stringify(compress(arr)));
since the motivation here is to reduce the size of the stored arrays, consider using something like gzip-js to compress your data.
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.