How to transpose array of object in javascript - javascript

I want to transpose values from 2 objects to 3 objects.In first object I want 1st value from each objects etc.
If 2 objects with 3 values then after transpose it will become 3 objects with two values.
before transpose
data is
obj 0:
0:"17"
1:0.052708692712917476
2:0.05170448850051073
3:0.036428533456315845
obj 1:
0:"16"
1:0.039474102915939856
2:0.04788765943666215
3:0.03651675504080556
After transpose I want following obj
obj 0:
0:0.052708692712917476 //1st value of 17 i.e obj 0
1:0.039474102915939856 //1st value of 16 i.e obj 1
obj 1:
0:0.05170448850051073 //2nd value of 17 i.e obj 0
1:0.04788765943666215 //2nd value of 16 i.e obj 1
obj 2:
0:0.036428533456315845
1:0.03651675504080556

You could transpose by getting the values and skipping the first property of the inner objects.
var data = { 0: { 0: "17", 1: 0.052708692712917476, 2: 0.05170448850051073, 3: 0.036428533456315845 }, 1: { 0: "16", 1: 0.039474102915939856, 2: 0.04788765943666215, 3: 0.03651675504080556 } },
result = Object.values(data).reduce(
(r, a, i) => (Object.values(a).slice(1).forEach((v, j) => (r[j] = r[j] || {})[i] = v), r),
{}
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES5
var data = { 0: { 0: "17", 1: 0.052708692712917476, 2: 0.05170448850051073, 3: 0.036428533456315845 }, 1: { 0: "16", 1: 0.039474102915939856, 2: 0.04788765943666215, 3: 0.03651675504080556 } },
result = {};
Object.keys(data).forEach(function (k, i) {
Object.keys(data[k]).slice(1).forEach(function (l, j) {
result[j] = result[j] || {};
result[j][i] = data[k][l];
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With only 2 objects and 2 properties?
Really easy, by accessing their properties directly!
var object1 = {
p11: v11
p12: v12,
p13: v13
}
var object2 = {
p21: v21
p22: v22,
p23: v23
}
You can use 2 notations: dot and array. And you are gonna need an additional helper variable so you don't step over property in 1 object before you transfer it to other.
Dot notation:
var helper = null;
helper = object1.v1
object1.v1 = object2.v2;
object2.v2 = helper;
Array-like or brackets notation:
var helper = null;
helper = object1.v1
object1["v1"] = object2.["v2"];
object2.["v2"] = helper;
It's hard to read what exactly transformation you wanna since but this is a basic simple way to let's say exchange properties of 2 objects. You can rinse and repeat this principle for multiple exchanges.
Remember, don't write new value over old one before you put old value in an object somewhere.
Oh, now that you made a proper example in question I see what you need. You need to chunk down 2 big objects of coordinates into smaller chunks each having a property from one. I wouldn't call that transpose, at least not by mathematical definition of it.
You need a function actually to give it 2 objects and it returns an array of small objects (ones with 2 properties). I hope those are object literals because unless you can number the properties by name (you have 1, 2, 3 and so on) in JS there is no way to ensure order of properties in object. Arrays are special objects used for that.
Oke, assuming you posted literals (only in inpropper syntax) let's write a function:
var getCoordinates = function (obA, obB){
var o1 = null;
var o2 = null;
var coordinatesArray = [];
// determine which object under property 0 has bigger value to know order
if (obA[0] < obB[0]) {
o1 = obA;
o2 = obB;
}
else {
o2 = obA;
o1 = obB;
}
// get value pairs assuming both objects have same number of properties
// if not, get as much as you can until one object runs out of coordinates
for (i=1; true; i++;){ // start at 1, 0 is reserved for object order
if (o1.hasOwnProperty(i+"") && o2.hasOwnProperty(i+""){
var coordinatePair = {};
coordinatePair["0"] = o2.[i+""];
coordinatePair["1"] = o1.[i+""];
coordinatesArray.push(coordinatePair);
}
else break;
}
return coordinatesArray;
}
}
Written purely from the head so I might have missed syntax (I am on tablet). But it should demo you the right idea.

Related

How to duplicate elements in a js array without creating "dependent elements"?

I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see #Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:
function duplicateElements(array, times) {
return array.reduce((res, current) => {
return res.concat(Array(times).fill(current));
}, []);
}
var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;
console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4
As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?
The problem is that you're passing the reference to the original object in Array(times).fill(current) .
In this case the two copies of the first {a:2} are the same copy of the original (They reference to the same space in memory) so if you change one, the two of them will change as they reference the same object in memory.
You have to make a deepcloning function or maybe spread the object inside a new one. You can change your original function to work with objects and primitives like this:
function duplicateElements(elementsArray, times) {
//Make a new placeholder array
var newArray = [];
//Loop the array of elements you want to duplicate
for (let index = 0; index < elementsArray.length; index++) {
//Current element of the array of element
var currentElement = elementsArray[index];
//Current type of the element to check if it is an object or not
var currentType = typeof currentElement
//Loop over the times you want to copy the element
for (let index = 0; index < times; index++) {
//If the new element is not an object
if (currentType !== "object" && currentType){
//append the element
newArray.push(currentElement)
//if it is an Object
} else if (currentType === "object" && currentType){
//append an spreaded new Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
newArray.push({...currentElement})
}
}
}
return newArray;
}
This is not the optimal way to do this, but I think that maybe you're new to javascript and is better to learn the old way of looping before using more Array functionalities (as the answer from Jonas Wilms, that is also a good answer).
I would recommend javascript.info and eloquent javascript to learn more about the language
The main reason for this as specified in the Array.fill documentation is that when dealing with objects it will copy by reference:
When fill gets passed an object, it will copy the reference and fill
the array with references to that object.
With lodash (and _.cloneDeep) that is one line like this:
let dubFn = (arr, t=1) =>
_.concat(arr, _.flatMap(_.times(t, 0), x => _.cloneDeep(arr)))
let r1 = dubFn([{a:1},{b:3}]) // no parameter would mean just 1 dub
let r2 = dubFn([{a:1},{b:3},5,[1]], 2) // 2 dublicates
r1[0].a = 3
r2[0].a = 3
console.log(r1)
console.log(r2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Note that this now works with arrays/objects and primitives.
The idea is to use _.concat to return a new concatenated version of the input array with a combination of few functions which on the end return an array of cloned objects. We use _.times to return an array of in this case t elements and then for each of those elements we replace with a deep clone of the array. _.flatMap is needed to flatten the end result since we end up having array of arrays after the _.times call.
With ES6 you can do something like this:
let dubElements = (arr, t) =>
[...arr, ...new Array(t).fill().flatMap(x => arr.map(y => ({...y})))]
let r1 = dubElements([{a:1},{b:3}])
let r2 = dubElements([{a:1},{b:3}],2)
r1[0].a = 3
r2[0].a = 3
console.log(r1)
console.log(r2)
Where we concat arrays via the spread operator and we use new Array(t) to create the new duplicates array and make sure we fill it with undefined in this case after which we flatMap the results (which we map through the clone via the spread operator again.
Note that this works for your use case specifically. If you want to make it more generic you have to expand more in the last map function etc.
If you want to preserve the order of the elements you can do something like this:
let dubElements = (arr, t=1) => {
let _result = []
arr.forEach(x => {
for(let i=0; i<t+1; i++) {
_result.push({...x})
}
})
return _result
}
let result = dubElements([{a:1},{b:3}],2)
result[0].a = 3
console.log(result)
Replace
Array(times).fill(current)
which will add one reference to current multiple times to the array with:
Array.from({ length: times }, () => ({...current }))
which will shallow clone current. Note that the code will then only work with objects though, not with primitives.
I'd do:
const duplicateElements = (array, length) =>
array.flatMap(current => Array.from({ length }, () => ({ ...current }));

How to keep an array with objects immutable in javascript?

I want to make an array based on two arrays - "ideaList" and "endorsements" declared globally. As ideaList and endorsements are used in other parts of the program I need them to be immutable, and I thought that .map and .filter would keep this immutability.
function prepareIdeaArray(){
var preFilteredIdeas=ideaList
.filter(hasIdeaPassedControl)
.map(obj => {obj.count = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber)
.reduce((sum, x)=>sum+x.count,0);
obj.like = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber && x.who===activeUser)
.reduce((sum, x)=>sum+x.count,0)===0?false:true
obj.position = generatePosition(obj.status)
obj.description = obj.description.replace(/\n/g, '<br>')
return obj;});
preFilteredIdeas.sort(compareOn.bind(null,'count',false)).sort(compareOn.bind(null,'position',true))
return preFilteredIdeas;
}
However, when I console.log ideaList after this function has been executed, I remark that objects of the array all have the "count", "like", "position" properties with values, which proves that the array has been mutated.
I tried by using .map only, but same result.
Would you know how I could prevent ideaList to get mutated? Also I would like to avoid to use const, as I declare ideaList globally first, and then assign to it some data in another function.
You're not mutating the array itself but rather the objects that the array contains references to. .map() creates a copy of the array but the references contained in it points to the exact same objects as the original, which you've mutated by adding properties directly to them.
You need to make copies of these objects too and add the properties to these copies. A neat way to do this is to use object spread in .map() callback:
.map(({ ...obj }) => {
obj.count = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber)
...
If your environment doesn't support object spread syntax, clone the object with Object.assign():
.map(originalObj => {
const obj = Object.assign({}, originalObj);
obj.count = endorsements
.filter(x=>x.ideaNumber===obj.ideaNumber)
...
In JS, the objects are referenced. When created, in other words, you get the object variable to point to a memory location which intends to be holding a meaningful value.
var o = {foo: 'bar'}
The variable o is now point to a memory which has {foo: bar}.
var p = o;
Now the variable p too is pointing to the same memory location. So, if you change o, it will change p too.
This is what happens inside your function. Even though you use Array methods which wouldn't mutate it's values, the array elements themselves are objects which are being modified inside the functions. It creates a new array - but the elements are pointing to the same old memory locations of the objects.
var a = [{foo: 1}]; //Let's create an array
//Now create another array out of it
var b = a.map(o => {
o.foo = 2;
return o;
})
console.log(a); //{foo: 2}
One way out is to create a new object for your new array during the operation. This can be done with Object.assign or latest spread operator.
a = [{foo: 1}];
b = a.map(o => {
var p = {...o}; //Create a new object
p.foo = 2;
return p;
})
console.log(a); // {foo:1}
To help having immutability in mind you could think of your values as primitives.
1 === 2 // false
'hello' === 'world' // false
you could extend this way of thinking to non-primitives as well
[1, 2, 3] === [1, 2, 3] // false
{ username: 'hitmands' } === { username: 'hitmands' } // false
to better understand it, please have a look at MDN - Equality Comparisons and Sameness
how to force immutability?
By always returning a new instance of the given object!
Let's say we have to set the property status of a todo. In the old way we would just do:
todo.status = 'new status';
but, we could force immutability by simply copying the given object and returning a new one.
const todo = { id: 'foo', status: 'pending' };
const newTodo = Object.assign({}, todo, { status: 'completed' });
todo === newTodo // false;
todo.status // 'pending'
newTodo.status // 'completed'
coming back to your example, instead of doing obj.count = ..., we would just do:
Object.assign({}, obj, { count: ... })
// or
({ ...obj, count: /* something */ })
there are libraries that help you with the immutable pattern:
Immer
ImmutableJS
You use the freeze method supplying the object you want to make immutable.
const person = { name: "Bob", age: 26 }
Object.freeze(person)
You could use the new ES6 built-in immutability mechanisms, or you could just wrap a nice getter around your objects similar to this
var myProvider = {}
function (context)
{
function initializeMyObject()
{
return 5;
}
var myImmutableObject = initializeMyObject();
context.getImmutableObject = function()
{
// make an in-depth copy of your object.
var x = myImmutableObject
return x;
}
}(myProvider);
var x = myProvider.getImmutableObject();
This will keep your object enclosed outside of global scope, but the getter will be accessible in your global scope.
You can read more on this coding pattern here
One easy way to make "copies" of mutable objects is to stringify them into another object and then parse them back into a new array. This works for me.
function returnCopy(arrayThing) {
let str = JSON.stringify(arrayThing);
let arr = JSON.parse(str);
return arr;
}
Actually, you can use spread opreator to make the original array stay unchanged, below y is the immutable array example:
const y = [1,2,3,4,5];
function arrayRotation(arr, r, v) {
for(let i = 0; i < r; i++) {
arr = [...y]; // make array y as immutable array [1,2,3,4,5]
arr.splice(i, 0, v);
arr.pop();
console.log(`Rotation ${i+1}`, arr);
}
}
arrayRotation(y, 3, 5)
If you don't use the spread operator, the y array will get changed when loop is running time by time.
Here is the mutable array result:
const y = [1,2,3,4,5];
function arrayRotation(arr, r, v) {
for(let i = 0; i < r; i++) {
arr = y; // this is mutable, because arr and y has same memory address
arr.splice(i, 0, v);
arr.pop();
console.log(`Rotation ${i+1}`, arr);
}
}
arrayRotation(y, 3, 5)
You assign these properties in your map function, you need to change this. (Just declare an empty object instead of using your current obj)

Why does changing the value of a property change the value for all similarly named properties in an array?

Why does changing the value of a property change the value for all similar properties in an array and how do I get it to work right without using the this keyword for 'name'?
let Object = {
'name' : 'Test Object'
}
let Array = []
Array.push(Object)
Array.push(Object)
Array.push(Object)
Array[0]['name'] = 'Changed'
console.log(Array) // expect only the first name to change, but all 3 change...
You aren't changing "similarly named" objects, you are changing the same object.
For non-primitives (basically everything that isn't a string, number, or boolean), they are passed by reference. That means when you add them to something like an array or pass them to a function, you are basically passing their address. If you pass it 3 times, they all point to the same address; there is still only one copy. Change one, and you change them all.
const a = { b: 1 };
const arr = [a, a, a];
// All the same object
console.log(arr[0] === arr[1], arr[1] === arr[2], a === arr[0]);
a.b = 5;
// All 3 changed, because it is the same thing
console.log(arr.map(a => a.b));
function someFunc(obj) { obj.b = 10 };
someFunc(a);
// changed from inside function, same object
console.log(a.b);
If you want to create a handful of objects that all start the same, but then are able to change afterwards, you need to create the objects in a loop:
const template = { name: 'a' };
const arr = [];
for (let i = 0; i < 3; i++) {
arr.push({ ...template }); // or: arr.push(Object.create({}, template))
}
arr[1].name = 'b';
arr[2].name = 'c';
console.log(arr);
Or, even more concisely:
// Creates a new Array with 3 records and then puts a copy of the template in each.
const template = { name: 'a' };
const arr = new Array(3).fill(1).map(() => ({ ...template }));
// or (without needing template variable):
// const arr = new Array(3).fill(1).map(() => ({ name: 'a' }))
arr[1].name = 'b';
arr[2].name = 'c';
console.log(arr);
When you invoke Array.push(Object), you're pushing a reference to the same object into the array 3 times. Push does not make a copy of Object - only 1 Object exists.
If you want 3 identical objects in an array, try something like this:
let vArray = []
for(i = 0; i <= 2; i++) {
//We're going to loop this 3 times, creating 3 different
//objects and pushing each of them into the array
let vObject = {
'name' : 'Test Object'
}
vArray.push(vObject)
}
vArray[0]['name'] = 'Changed'
console.log(vArray) // Only the first one will have been changed.
The answer I was looking for was to change the syntax in my answer to Array.push({...Object}). This creates a 'new' object to be pushed, with only 5 additional characters...
I didn't know 'object spread syntax' essentially did this.

How to create and push values into an 3 dimensional array

I need help with making a 3-dimensional array, my objective is e.g:
Just for graphic illustration :-), see row below
[category: 1[subcategories: 1[subsubcategories: 1,2],2[subsubcategories: 3,4]]
In scenario above the user has selected:
category 1
subcategories: 1
subsubcategories: 1,2
subcategories: 2
subsubcategories: 3,4
I can then with these values create a string like: 1^1:1,2^2:3,4
Hope anyone understands :)
Use objects instead of arrays. When you use string indexes on array elements the array gets turned into an object and some of the array methods might not work properly afterwards. Why not just use an object from the beginning then.
WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results.
this is taken from https://www.w3schools.com.
Here is an example of how to use it:
// Object = {} instead of array = []
var myObject = {};
myObject['category'] = {1: {subcategories: {1:[1,2], 2: [3,4] }} };
// For example
var anotherObject = {};
anotherObject['category'] = {1: {}, 2: {}};
anotherObject['category'][1] = [1,2];
anotherObject['category'][2] = [3,4];
// Edit: example 3
// ---------------
// result from database JSON format
var resultFromDB = {"category": {"1": {"subcategories": {"1": {"subsubcategories": [1,2]}, "2": {"subsubcategories": [3,4] }}}} };
// example of building new object from input
var myNewObject = {};
var type;
// go through the first level
for(var index in resultFromDB)
{
// in case you needed this is how you would check type of input
type = typeof resultFromDB[index];
if((type === "object") && (type !== null)) // check if its an object
{
// set myNewObject[index] to new object
myNewObject[index] = {};
// go through second level
for(var subIndex in resultFromDB[index])
{
// set myNewObject[index][subIndex] as new object
myNewObject[index][subIndex] = {};
// go through third level
for(var subSubIndex in resultFromDB[index][subIndex])
{
// simply use an '=' to get all from that level
myNewObject[index][subIndex][subSubIndex] = resultFromDB[index][subIndex][subSubIndex];
}
}
}
}
console.log("This is the new object");
console.log(myNewObject);
console.log("\n");
console.log("This is the original object");
console.log(myNewObject);
// If you need to extract in multiple places you could make a function for quick access
function returnObject(incomingObject)
{
var myNewObject = {};
var type;
// ... copy paste here all the above code from example 3 except resultFromDB
return myNewObject;
}
// then just call it from anywhere
var theNewestObject = returnObject(resultFromDB);

Javascript multidimensional associated array error [duplicate]

There is the following query results: (key1 and key2 could be any text)
id key1 key2 value
1 fred apple 2
2 mary orange 10
3 fred banana 7
4 fred orange 4
5 sarah melon 5
...
and I wish to store the data in a grid (maybe as an array) looping all the records like this:
apple orange banana melon
fred 2 4 7 -
mary - 10 - -
sarah - - - 5
In PHP this would be really easy, using associative arrays:
$result['fred']['apple'] = 2;
But in JavaScript associative arrays like this doesn't work.
After reading tons of tutorial, all I could get was this:
arr=[];
arr[1]['apple'] = 2;
but arr['fred']['apple'] = 2; doesn't work.
I tried arrays of objects, but objects properties can't be free text.
The more I was reading tutorials, the more I got confused...
Any idea is welcome :)
Just use a regular JavaScript object, which would 'read' the same way as your associative arrays. You have to remember to initialize them first as well.
var obj = {};
obj['fred'] = {};
if('fred' in obj ){ } // can check for the presence of 'fred'
if(obj.fred) { } // also checks for presence of 'fred'
if(obj['fred']) { } // also checks for presence of 'fred'
// The following statements would all work
obj['fred']['apples'] = 1;
obj.fred.apples = 1;
obj['fred'].apples = 1;
// or build or initialize the structure outright
var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };
If you're looking over values, you might have something that looks like this:
var people = ['fred', 'alice'];
var fruit = ['apples', 'lemons'];
var grid = {};
for(var i = 0; i < people.length; i++){
var name = people[i];
if(name in grid == false){
grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
}
for(var j = 0; j < fruit.length; j++){
var fruitName = fruit[j];
grid[name][fruitName] = 0;
}
}
If it doesn't have to be an array, you can create a "multidimensional" JS object...
<script type="text/javascript">
var myObj = {
fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 },
mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 },
sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 }
}
document.write(myObj['fred']['apples']);
</script>
Javascript is flexible:
var arr = {
"fred": {"apple": 2, "orange": 4},
"mary": {}
//etc, etc
};
alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
alert(key + ": " + arr.fred[key]);
As I needed get all elements in a nice way I encountered this SO subject "Traversing 2 dimensional associative array/object" - no matter the name for me, because functionality counts.
var imgs_pl = {
'offer': { 'img': 'wer-handwritter_03.png', 'left': 1, 'top': 2 },
'portfolio': { 'img': 'wer-handwritter_10.png', 'left': 1, 'top': 2 },
'special': { 'img': 'wer-handwritter_15.png', 'left': 1, 'top': 2 }
};
for (key in imgs_pl) {
console.log(key);
for (subkey in imgs_pl[key]) {
console.log(imgs_pl[key][subkey]);
}
}
It appears that for some applications, there is a far simpler approach to multi dimensional associative arrays in javascript.
Given that the internal representation of all arrays are actually as objects of objects, it has been shown that the access time for numerically indexed elements is actually the same as for associative (text) indexed elements.
the access time for first-level associative indexed elements does not rise as the number of actual elements increases.
Given this, there may be many cases where it is actually better to use a concatenated string approach to create the equivalence of a multidimensional elements. For example:
store['fruit']['apples']['granny']['price'] = 10
store['cereal']['natural']['oats']['quack'] = 20
goes to:
store['fruit.apples.granny.price'] = 10
store['cereal.natural.oats.quack'] = 20
Advantages include:
no need to initialize sub-objects or figure out how to best combine objects
single-level access time. objects within objects need N times the access time
can use Object.keys() to extract all dimension information and..
can use the function regex.test(string) and the array.map function on the keys to pull out exactly what you want.
no hierarchy in the dimensions.
the "dot" is arbitrary - using underscore actually makes regex easier
there are lots of scripts for "flattening" JSON into and out of this format as well
can use all of the other nice array processing functions on keylist
You don't need to necessarily use Objects, you can do it with normal multi-dimensional Arrays.
This is my solution without Objects:
// Javascript
const matrix = [];
matrix.key1 = [
'value1',
'value2',
];
matrix.key2 = [
'value3',
];
which in PHP is equivalent to:
// PHP
$matrix = [
"key1" => [
'value1',
'value2',
],
"key2" => [
'value3',
]
];
Get the value for an array of associative arrays's property when the property name is an integer:
Starting with an Associative Array where the property names are integers:
var categories = [
{"1":"Category 1"},
{"2":"Category 2"},
{"3":"Category 3"},
{"4":"Category 4"}
];
Push items to the array:
categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});
Loop through array and do something with the property value.
for (var i = 0; i < categories.length; i++) {
for (var categoryid in categories[i]) {
var category = categories[i][categoryid];
// log progress to the console
console.log(categoryid + " : " + category);
// ... do something
}
}
Console output should look like this:
1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301
As you can see, you can get around the associative array limitation and have a property name be an integer.
NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.
Don't use an array, use an object.
var foo = new Object();
<script language="javascript">
// Set values to variable
var sectionName = "TestSection";
var fileMap = "fileMapData";
var fileId = "foobar";
var fileValue= "foobar.png";
var fileId2 = "barfoo";
var fileValue2= "barfoo.jpg";
// Create top-level image object
var images = {};
// Create second-level object in images object with
// the name of sectionName value
images[sectionName] = {};
// Create a third level object
var fileMapObj = {};
// Add the third level object to the second level object
images[sectionName][fileMap] = fileMapObj;
// Add forth level associate array key and value data
images[sectionName][fileMap][fileId] = fileValue;
images[sectionName][fileMap][fileId2] = fileValue2;
// All variables
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);
// All keys with dots
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);
// Mixed with a different final key
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);
// Mixed brackets and dots...
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);
// This will FAIL! variable names must be in brackets!
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);
// Produces: "Example 5 Value: undefined".
// This will NOT work either. Values must be quoted in brackets.
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);
// Throws and exception and stops execution with error: fileMapData is not defined
// We never get here because of the uncaught exception above...
alert ("The End!");
</script>
var myObj = [];
myObj['Base'] = [];
myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['Base']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1'] = [];
myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
console.log(myObj);
if ('Base' in myObj) {
console.log('Base found');
if ('Base.panel.panel_base' in myObj['Base']) {
console.log('Base.panel.panel_base found');
console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);
myObj['Base']['Base.panel.panel_base'] = 'new Value';
console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
}
}
Output:
Base found
Base.panel.panel_base found
old value: Base
new value: new Value
The array operation works. There is no problem.
Iteration:
Object.keys(myObj['Base']).forEach(function(key, index) {
var value = objcons['Base'][key];
}, myObj);

Categories

Resources