javascript object - Dynamically setting a nested value using recursive function - javascript

I am trying to set one of the nested subobject properties, but the nested level is dynamic.
how can I dynamically set the nested properties?
It's working only one level properties,i can't set next inner level....
my code:
function deSerialize(qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode)
{
if (currentIndex == (qualifiedNameArray.length - 1)){
resultJSON [qualifiedNameArray[currentIndex++]] = valueToBeInitializedForFinalNode;
}
else
{
resultJSON [qualifiedNameArray[currentIndex++]] = {};
}
if (currentIndex < qualifiedNameArray.length)
deSerialize( qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode);
return resultJSON;
}
var results = {"columnname":"person.name.first", "varcharvalue":"david", "objecttype" : "user"};
var valueToBeInitializedForFinalNode = results["varcharvalue"];
var qualifiedNameArray = results["columnname"].split('.');
var resultJSON = {};
deSerialize(qualifiedNameArray, 0, resultJSON, valueToBeInitializedForFinalNode);

A simple solution might be, not sure if this is what you are looking for:
function makeObj(arry, initValue){
var obj = {}, objRef = obj, idx = 0;
while(idx < arry.length -1){
obj[arry[idx]] = {};
obj = obj[arry[idx]];
idx++;
}
obj[arry[idx]] = initValue;
return objRef;
}
usage:
resultJSON = makeObj( qualifiedNameArray, valueToBeInitializedForFinalNode);
another way is:
function makeObj(objRef, arry, initValue){
var obj = objRef, idx = 0;
while(idx < arry.length -1){
if(!obj[arry[idx]]) obj[arry[idx]] = {};
obj = obj[arry[idx]];
idx++;
}
if(!obj[arry[idx]]) obj[arry[idx]] = initValue;
}
this way, you do not change any values that might have been already present, usage:
makeObj( resultJSON, qualifiedNameArray, valueToBeInitializedForFinalNode);

Related

JavaScript: Convert dot notation string to array [duplicate]

I'm trying to create a JS object dynamically providing a key and a value. The key is in dot notation, so if a string like car.model.color is provided the generated object would be:
{
car: {
model: {
color: value;
}
}
}
The problem has a trivial solution if the key provided is a simple property, but i'm struggling to make it work for composed keys.
My code:
function (key, value) {
var object = {};
var arr = key.split('.');
for(var i = 0; i < arr.length; i++) {
object = object[arr[i]] = {};
}
object[arr[arr.length-1]] = value;
return object;
}
your slightly modified code
function f(key, value) {
var result = object = {};
var arr = key.split('.');
for(var i = 0; i < arr.length-1; i++) {
object = object[arr[i]] = {};
}
object[arr[arr.length-1]] = value;
return result;
}
In the loop you should set all of the props but the last one.
Next set the final property and all set.
If you're using lodash you could use _.set(object, path, value)
const obj = {}
_.set(obj, "car.model.color", "my value")
console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Use namespace pattern, like the one Addy Osmani shows: http://addyosmani.com/blog/essential-js-namespacing/
Here's the code, pasted for convenience, all credit goes to Addy:
// top-level namespace being assigned an object literal
var myApp = myApp || {};
// a convenience function for parsing string namespaces and
// automatically generating nested namespaces
function extend( ns, ns_string ) {
var parts = ns_string.split('.'),
parent = ns,
pl, i;
if (parts[0] == "myApp") {
parts = parts.slice(1);
}
pl = parts.length;
for (i = 0; i < pl; i++) {
//create a property if it doesnt exist
if (typeof parent[parts[i]] == 'undefined') {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
}
// sample usage:
// extend myApp with a deeply nested namespace
var mod = extend(myApp, 'myApp.modules.module2');
function strToObj(str, val) {
var i, obj = {}, strarr = str.split(".");
var x = obj;
for(i=0;i<strarr.length-1;i++) {
x = x[strarr[i]] = {};
}
x[strarr[i]] = val;
return obj;
}
usage: console.log(strToObj("car.model.color","value"));
I would use a recursive method.
var createObject = function(key, value) {
var obj = {};
var parts = key.split('.');
if(parts.length == 1) {
obj[parts[0]] = value;
} else if(parts.length > 1) {
// concat all but the first part of the key
var remainingParts = parts.slice(1,parts.length).join('.');
obj[parts[0]] = createObject(remainingParts, value);
}
return obj;
};
var simple = createObject('simple', 'value1');
var complex = createObject('more.complex.test', 'value2');
console.log(simple);
console.log(complex);
(check the console for the output)
Here's a recursive approach to the problem:
const strToObj = (parts, val) => {
if (!Array.isArray(parts)) {
parts = parts.split(".");
}
if (!parts.length) {
return val;
}
return {
[parts.shift()]: strToObj(parts, val)
};
}

unexpected token break in ternary conditional

The function below is intended to return the values from a (potentially nested) object as an array - with the list parameter being any object. If I move my break statement to after the for loop, I don't get any errors, but of course then my function doesn't behave as needed. What's wrong with the way I'm using break?
function listToArray(list) {
var objectArray = [];
function objectPeeler() {
let peel = Object.getOwnPropertyNames(list);
for(var i = 0; i < peel.length; i++) {
list[peel[i]] && typeof list[peel[i]] != 'object' ?
objectArray.push(list[peel[i]]):
list[peel[i]] ?
(list = list[peel[i]], objectPeeler()) :
break;
}
return objectArray;
}
objectPeeler();
}
In case anyone else has this issue: ternary operators only work with value expressions, not statements (like break) and aren't meant to be used in these cases.
This works:
function listToArray(list) {
var objectArray = [];
function objectPeeler() {
let peel = Object.getOwnPropertyNames(list);
for(var i = 0; i < peel.length; i++) {
list[peel[i]] != null && typeof list[peel[i]] != 'object' ?
objectArray.push(list[peel[i]]):
list[peel[i]] ?
(list = list[peel[i]], objectPeeler()): null;
}
}
objectPeeler();
return objectArray;
}
But using the jquery .next method allows a better solution:
function listToArray(list) {
var array = [];
for (var obj = list; obj; obj = obj.next)
array.push(obj.value);
return array;
}
why not writing something like this :
var obj = { 0: "a", 1: "b", 2: "c"}; //test target
var objectArray = [];
var keyArray = Object.getOwnPropertyNames(obj);
for (var i = 0; i < keyArray.length; i++) objectArray.push(obj[keyArray[i]]);
console.log(objectArray); // test result

How to do I unshift/shift single value and multiple values using custom methods?

I have prototypes to recreate how array methods work, pop/push/shift/etc, and I would like to extend the functionality to do the following:
Push/Pop/shift/unshift multiple values
array.push(0);
array.push(1);
array.push(2);
expect(array.pop()).to.be(2);
expect(array.pop()).to.be(1);
expect(array.pop()).to.be(0);
Push/Pop/unshift/etc single values
array.push(0);
array.push(1);
expect([0,1]);
array.pop(1);
expect([0]);
My assumption is that I would need a global array variable to store the elements. Is that the right?
Here is my code:
var mainArray = []; // array no longer destroyed after fn() runs
function YourArray(value) {
this.arr = mainArray; // looks to global for elements | function?
this.index = 0;
var l = mainArray.length;
if(this.arr === 'undefined')
mainArray += value; // add value if array is empty
else
for(var i = 0; i < l ; i++) // check array length
mainArray += mainArray[i] = value; // create array index & val
return this.arr;
}
YourArray.prototype.push = function( value ) {
this.arr[ this.index++ ] = value;
return this;
};
YourArray.prototype.pop = function( value ) {
this.arr[ this.index-- ] = value;
return this;
};
var arr = new YourArray();
arr.push(2);
console.log(mainArray);
My assumption is that I would need a global array variable to store
the elements. Is that the right?
No. That is not right.
You want each array object to have its own, independent set of data. Otherwise, how can you have multiple arrays in your program?
function YourArray(value) {
this.arr = []; // This is the data belonging to this instance.
this.index = 0;
if(typeof(value) != 'undefined')) {
this.arr = [value];
this.index = 1;
}
}
////////////////////////////////////
// Add prototype methods here
///////////////////////////////////
var array1 = new YourArray();
var array2 = new YourArray();
array1.push(2);
array1.push(4);
array2.push(3);
array2.push(9);
// Demonstrate that the values of one array
// are unaffected by the values of a different array
expect(array1.pop()).to.be(4);
expect(array2.pop()).to.be(9);
It's a bit late for this party, admitted but it nagged me. Is there no easy (for some larger values of "easy") way to do it in one global array?
The standard array functions work as in the following rough(!) sketch:
function AnotherArray() {
this.arr = [];
// points to end of array
this.index = 0;
if(arguments.length > 0) {
for(var i=0;i<arguments.length;i++){
// adapt if you want deep copies of objects
// and/or take a given array's elements as
// individual elements
this.arr[i] = arguments[i];
this.index++;
}
}
}
AnotherArray.prototype.push = function() {
// checks and balances ommitted
for(var i=0;i<arguments.length;i++){
this.arr[ this.index++ ] = arguments[i];
}
return this;
};
AnotherArray.prototype.pop = function() {
this.index--;
return this;
};
AnotherArray.prototype.unshift = function() {
// checks and balances ommitted
var tmp = [];
var alen = arguments.length;
for(var i=0;i<this.index;i++){
tmp[i] = this.arr[i];
}
for(var i=0;i<alen;i++){
this.arr[i] = arguments[i];
this.index++;
}
for(var i=0;i<tmp.length + alen;i++){
this.arr[i + alen] = tmp[i];
}
return this;
};
AnotherArray.prototype.shift = function() {
var tmp = [];
for(var i=1;i<this.index;i++){
tmp[i - 1] = this.arr[i];
}
this.arr = tmp;
this.index--;
return this;
};
AnotherArray.prototype.isAnotherArray = function() {
return true;
}
AnotherArray.prototype.clear = function() {
this.arr = [];
this.index = 0;
}
AnotherArray.prototype.fill = function(value,length) {
var len = 0;
if(arguments.length > 1)
len = length;
for(var i=0;i<this.index + len;i++){
this.arr[i] = value;
}
if(len != 0)
this.index += len;
return this;
}
// to simplify this example
AnotherArray.prototype.toString = function() {
var delimiter = arguments.length > 0 ? arguments[0] : ",";
var output = "";
for(var i=0;i<this.index;i++){
output += this.arr[i];
if(i < this.index - 1)
output += delimiter;
}
return output;
}
var yaa = new AnotherArray(1,2,3);
yaa.toString(); // 1,2,3
yaa.push(4,5,6).toString(); // 1,2,3,4,5,6
yaa.pop().toString(); // 1,2,3,4,5
yaa.unshift(-1,0).toString(); // -1,0,1,2,3,4,5
yaa.shift().toString(); // 0,1,2,3,4,5
var yaa2 = new AnotherArray();
yaa2.fill(1,10).toString(); // 1,1,1,1,1,1,1,1,1,1
Quite simple and forward and took only about 20 minutes to write (yes, I'm a slow typist). I would exchange the native JavaScript array in this.arr with a double-linked list if the content can be arbitrary JavaScript objects which would make shift and unshift a bit less memory hungry but that is obviously more complex and slower, too.
But to the main problem, the global array. If we want to use several individual chunks of the same array we need to have information about the starts and ends of the individual parts. Example:
var globalArray = [];
var globalIndex = [[0,0]];
function YetAnotherArry(){
// starts at the end of the last one
this.start = globalIndex[globalIndex.length-1][1];
this.index = this.start;
// position of the information in the global index
this.pos = globalIndex.length;
globalIndex[globalIndex.length] = [this.start,this.index];
}
So far, so well. We can handle the first array without any problems. We can even make a second one but the moment the first one wants to expand its array we get in trouble: there is no space for that. The start of the second array is the end of the first one, without any gap.
One simple solution is to use an array of arrays
globalArray = [
["first subarray"],
["second subarray"],
...
];
We can than reuse what we already wrote in that case
var globalArray = [];
function YetAnotherArray(){
// open a new array
globalArray[globalArray.length] = [];
// point to that array
this.arr = globalArray[globalArray.length - 1];
this.index = 0;
}
YetAnotherArray.prototype.push = function() {
for(var i=0;i<arguments.length;i++){
this.arr[ this.index++ ] = arguments[i];
}
return this;
};
// and so on
But for every new YetAnotherArray you add another array to the global array pool and every array you abandon is still there and uses memory. You need to manage your arrays and delete every YetAnotherArray you don't need anymore and you have to delete it fully to allow the GC to do its thing.
That will leave nothing but gaps in the global array. You can leave it as it is but if you want to use and delete thousands you are left with a very sparse global array at the end. Or you can clean up. Problem:
var globalArray = [];
function YetAnotherArray(){
// add a new subarray to the end of the global array
globalArray[globalArray.length] = [];
this.arr = globalArray[globalArray.length - 1];
this.index = 0;
this.pos = globalArray.length - 1;
}
YetAnotherArray.prototype.push = function() {
for(var i=0;i<arguments.length;i++){
this.arr[ this.index++ ] = arguments[i];
}
return this;
};
YetAnotherArray.prototype.toString = function() {
var delimiter = arguments.length > 0 ? arguments[0] : ",";
var output = "";
for(var i=0;i<this.index;i++){
output += this.arr[i];
if(i < this.index - 1)
output += delimiter;
}
return output;
}
// we need a method to delete an instance
YetAnotherArray.prototype.clear = function() {
globalArray[this.pos] = null;
this.arr = null;
this.index = null;
};
YetAnotherArray.delete = function(arr){
arr.clear();
delete(arr);
};
// probably won't work, just a hint in case of asynch. use
var mutex = false;
YetAnotherArray.gc = function() {
var glen, indexof, next_index, sub_len;
indexof = function(arr,start){
for(var i = start;i<arr.length;i++){
if (arr[i] == null || arr[i] == undefined)
return i;
}
return -1;
};
mutex = true;
glen = globalArray.length;
sublen = 0;
for(var i = 0;i<glen;i++){
if(globalArray[i] == null || globalArray[i] == undefined){
next_index = indexof(globalArray,i);
if(next_index == -1){
break;
}
else {
globalArray[i] = globalArray[next_index + 1];
globalArray[next_index + 1] = null;
sublen++;
}
}
}
globalArray.length -= sublen - 1;
mutex = false;
};
var yaa_1 = new YetAnotherArray();
var yaa_2 = new YetAnotherArray();
var yaa_3 = new YetAnotherArray();
var yaa_4 = new YetAnotherArray();
yaa_1.push(1,2,3,4,5,6,7,8,9).toString(); // 1,2,3,4,5,6,7,8,9
yaa_2.push(11,12,13,14,15,16).toString(); // 11,12,13,14,15,16
yaa_3.push(21,22,23,24,25,26,27,28,29).toString();// 21,22,23,24,25,26,27,28,29
yaa_4.push(311,312,313,314,315,316).toString(); // 311,312,313,314,315,316
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
11,12,13,14,15,16
21,22,23,24,25,26,27,28,29
311,312,313,314,315,316
*/
YetAnotherArray.delete(yaa_2);
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
21,22,23,24,25,26,27,28,29
311,312,313,314,315,316
*/
YetAnotherArray.gc();
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
21,22,23,24,25,26,27,28,29
311,312,313,314,315,316
*/
But, as you might have guessed already: it doesn't work.
YetAnotherArray.delete(yaa_3); // yaa_3 was 21,22,23,24,25,26,27,28,29
globalArray.join("\n");
/*
1,2,3,4,5,6,7,8,9
21,22,23,24,25,26,27,28,29
*/
We would need another array to keep all positions. Actual implementation as an exercise for the reader but if you want to implement a JavaScript like array, that is for arbitrary content you really, really, really should use a doubly-linked list. Or a b-tree. A b+-tree maybe?
Oh, btw: yes, you can do it quite easily with a {key:value} object, but that would have squeezed all the fun out of the job, wouldn't it? ;-)

Javascript: attach child several deep to object?

If I want to iterate through a list like this:
var inputArray = [
'CHILD0',
'PARENT0_CHILD1',
'PARENT1_PARENT2_CHILD2',
'PARENT1_PARENT3_CHILD3',
'PARENT1_PARENT3_CHILD4'
];
And have it return an object like so:
var resultObject = {
CHILD0: null,
PARENT0: {CHILD1: null},
PARENT1: {
PARENT2: {CHILD2: null},
PARENT3: {
CHILD3: null,
CHILD4: null
}
}
};
How could I iterate through the array to return the result?
I've got something like this:
function iterateArray (inputArray) {
var _RESULT = {};
for (var i = 0; i < inputArray.length; i += 1) {
var _inputName = inputArray[i];
var _inputNameArray = _input.split('_');
var _ref;
for (var n = 0; n < _inputNameArray.length; n += 1) {
//...?
}
_RESULT[_ref] = null;
}
return _RESULT;
}
var resultObject = iterateArray(inputArray);
Not sure what to do from this point. Think I might need a recursive function of sorts. Thoughts?
With minimal changes to your code:
function iterateArray (inputArray) {
var _RESULT = {};
for (var i = 0; i < inputArray.length; i += 1) {
var _inputName = inputArray[i];
var _inputNameArray = _inputName.split('_');
var _ref = _RESULT;
for (var n = 0; n < _inputNameArray.length - 1; n += 1) {
if (!_ref[_inputNameArray[n]]) _ref[_inputNameArray[n]] = {};
_ref = _ref[_inputNameArray[n]];
}
_ref[_inputNameArray[n]] = null;
}
return _RESULT;
}
You never need recursion, as it can always be unwrapped into iteration (and vice versa). Things are just sometimes much nicer one way or another.
EDIT: What's with all the underscores? :)
EDIT2: The key point to understanding this is reference sharing. For example:
For CHILD0, _ref = _RESULT means both of the variables are pointing at the same {}. When you do _ref['CHILD0'] = null, it is the same as doing _RESULT['CHILD0'] = null.
For PARENT0_CHILD1, first _ref = _RESULT as above, so _ref['PARENT0'] = {} is the same as _RESULT['PARENT0'] = {}. Then we switch the meaning of _ref to be the same thing as _RESULT['PARENT0']; when we assign _ref['CHILD1'] = null, it is the same as assigning _RESULT['PARENT0']['CHILD1'] = null.

Count in an array the number for each same value

My function is
var MyArray= [];
$('input:checked').each(function(index) {
MyArray= ($(this).attr('id') + ":" + $(this).val()).length;
});
My array is
Array [ "1:R1", "2:R2", "3:R3", "4:R1" ]
I would like to count the differents values and to get this object
Object {R1:2, R2:1, R3:1}
Instead of putting the values in an array and then get the values out of the array to process them and create an object, put them in the object to start with:
var map = {};
$('input:checked').each(function() {
var key = $(this).val();
if (key in map) {
map[key]++;
} else {
map[key] = 1;
}
});
Demo: http://jsfiddle.net/Guffa/0a35c6yp/
You can convert your var with this code :
var arr = [ "1:R1", "2:R2", "3:R3", "4:R1" ];
var obj = {};
for(var i=0, l=arr.length; i<l; i++) {
var parts = arr[i].split(':');
if(parts.length > 1) {
if(!obj[parts[1]]) {
obj[parts[1]] = 0;
}
obj[parts[1]]++
}
}
console.log(obj)
Or create directly the correct object :
var obj = {};
$('input:checked').each(function (index) {
var key = $(this).val();
if (!obj[key]) {
obj[key] = 0;
}
obj[key]++
});
Use a regex to capture the correct portion of the string, and add them as keys to the object, incrementing the value if it already exists:
var regex = /\d+:(R\d+)/
var obj = {};
arr.forEach(function (el) {
var key = el.match(regex)[1];
if (!obj[key]) obj[key] = 0;
obj[key]++;
});
DEMO
You could try something like that:
Write your Array into a Map and step up your value each time your map already knows the key.
for(var i = 0; i < myArray.length; i++){
var entry = myArray[i];
var key = entry.split(":")[1];
if(myMap.has(key))
myMap.set(key, myMap.get(key) + 1);
else
myMap.set(key, 1);
}
DEMO

Categories

Resources