Javascript is empty after filling with data - javascript

Javascript array is empty after filling with values
I tried this code:
var browserdata = new Array();
// Fill the array with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata); // This shows an empty array
It should show { "qqq" => "zzz", "zzz" => 1 }
Actual output is [] (empty array).

You need to use Object data type instead of Array. Using object structure, you can assign properties to it and corresponding value for that property to get the desired output as { "qqq" => "zzz", "zzz" => 1 }
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
You can also use the another approach, to assign the property at the time object is declared:
var browserdata = {
'qqq': 'zzz',
'rrr': 1
};
console.log(browserdata);

It will never return empty as there are data in the array, with your code it will return an output
[qqq: "zzz", rrr: 1]
If you want to get an output like { "qqq" => "zzz", "zzz" => 1 } , You should use objects .Objects are nothing but a grouping of data,
for example, consider a student array with different data sets.
here you could define individual data or data sets like
student['name'] = john ;
student['mark'] = 20;
OR
students =[{name : john , mark :20} ,{name : rick, mark :20} ]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://javascript.info/array
If new Array() is called with a single argument which is a number, then it creates an array without items, but with the given length.
It’s rarely used, because square brackets [] are shorter. Also there’s a tricky feature with it lets see.
var arr = new Array(2); // will it create an array of [2] ?
console.log( arr[0] ); // undefined! no elements.
console.log( arr.length ); // length 2
var browserdata = new Array();
browserdata[0] = "zzz";
browserdata[1] = 1;
console.log(browserdata);
console.log(browserdata.length);

That solution works for me. Initializing with {} rather than [] or new Array() works. Thanks.
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);

Only the positive integer keys of array object are displayed by default, but the rest of the properties can still be accessed and seen in the Google Chrome console.
var arr = []
arr[1] = 1
arr[-1] = -1
arr[.1] = .1
arr.a = 'a'
arr['b'] = 'b'
console.log( arr ) // [undefined, 1]
console.log( arr.b ) // "b"
console.log( { ...arr } ) // { "1": 1, "-1": -1, "0.1": 0.1, "a": "a", "b": "b" }

Related

Group array to an object in javascript

Hello apologies if this has been asked before but I can't search for the right term to find something useful.
Suppose if I had an array of
[
"0.001234", "2021-07-14 08:24:30"
"0.001245", "2021-07-14 01:04:24"
// etc etc ...
]
how would I change this to an object like so?
{
0: ["0.001234", "2021-07-14 08:24:30"]
1: ["0.001245", "2021-07-14 01:04:24"]
// etc etc ...
}
Edit - just noticed the format of your data - map reduce may not work for you, but still a similar principle:
let objForm = {}
for (let idx=0; idx<arrayForm.length; idx+=2) {
objForm[idx/2] = [ arrayForm[idx], arrayForm[idx+1] ]
}
Old answer:
You can use a reduce pattern.
let arrayForm = ["one", "two"]
let objForm = arrayForm.reduce((acc, val, idx) => ({
...acc,
[idx]: val
}), {})
console.log(objForm) // { 0: "one", 1: "two" }
The reduce method gets the accumulated value, the current value and the array index. In this case we are using the spread operator to add the next value to the object.
Note that the ( before the object definition is needed, so that JS doesn't confuse it with a code block.
Create a new object and then iterate over the array in element pairs and add them as a new array to the object.
const arr = [
'0.001234', '2021-07-14 08:24:30',
'0.001245', '2021-07-14 01:04:24'
];
const obj = {};
for (let i = 0; i < arr.length; i += 2) {
obj[i / 2] = [ arr[i], arr[i + 1] ];
}
console.log(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);

How can I push an object into an array?

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

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