Is this javascript declaration an array or some kind of object - javascript

Can someone please explain how the following javascript code:
var temp = {};
temp[0] = "a"
temp[1] = "b"
temp[2] = "c"
if different from an array like
var temp = new Array();
or
var temp = []
I don't really understand if the first example "temp = {}" can be considered an array or is it some kind of object?

var temp = {}; is an object with representation like Object {0: "a", 1: "b", 2: "c"}
var temp = [] is an array with representation like ["a", "b", "c"]
while var temp = new Array(); is again the same thing like temp = []
More detailed information here What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

The first one creates an object:
var temp = {};
The second one creates an array:
var temp = new Array();
In any case you can access them as they are an array:
var temp = {};
temp[1]="in object";
console.log(temp[1]);
same as
var temp = []
temp[1]="in array";
console.log(temp[1]);

Related

Javascript dynamic nested objects

I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.
I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?
here is the code:
var s = "key1.key2.key3.key4";
var a = s.split('.');
var obj = {};
var temp = obj;
for (var k =0; k < a.length; k++) {
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
why is there a var temp = obj?
what does this line do?:
temp = temp[a[k]] = {};
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Thanks for the feedback!
why is there a var temp = obj?
obj is a variable to hold the completed object. temp is a variable to hold each intermediate step of the object being built. temp starts out with the same value as obj so that the first iteration of the loop adds on to obj.
what does this line do?:
temp = temp[a[k]] = {};
Assign an empty object to a property in temp with the name a[k], where a[k] is one of the values in a.
Assign that new empty object to temp.
This could be written separately as two lines:
temp[a[k]] = {};
temp = temp[a[k]];
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Because the previous line assigns an empty object to temp.
Your question boils down to this (comments inline)
var x = {};
var y = x;
y[ "a" ] = {}; //reference to x stays so x also becomes { "a": {} }
y = y["a"]; //now y effectively becomes {} but has the same reference to y["a"] as assignment works right to left hence property `a` is becomes non-enumerable and hence shadowed.
console.log( "First Run" );
console.log( y ); //prints {}
console.log( x ); //prints { "a": {} }
y[ "a" ] = {}; //y still has a non-enumerable property `a`
y = y["a"]; //same as above y = y["a"], y again becomes {}
console.log( "Second Run" );
console.log( y ); //prints {} again
console.log( x ); //prints { "a": { "a": {} } }
Outputs
First Run
{}
{ "a": {} }
Second Run
{}
{ "a": {
"a": {} } }
Have added comments in code, hope it will be useful
var s = "key1.key2.key3.key4";
//split the string by dot(.) and create an array
var a = s.split('.');
//Creating an empty object
var obj = {};
var temp = obj;
//looping over the array
for (var k = 0; k < a.length; k++) {
//a[k] will be key1,key2,key3....
// temp is an object,square bracket is use to create a object key
// using a variable name
// variable name here is key1,key2....
//temp[a[k]] will initialize an empty object
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
It seems where you are iterating the array, in that temp object is newly creating and assigning key to obj.
temp = temp[a[k]] = {};
above line simply assigns a[index] value as a key to the new object and as a reference to obj the nested object is created.
for your question,
why is there a var temp = obj?
it copies obj object into temp variable
also, the console.log(temp) inside the loop always logs an empty object {}, why?
since you are recreating an empty object (or reassigning).

How to create key value pair using two arrays in JavaScript?

I have two arrays, keys and commonkeys.
I want to create a key-value pair using these two arrays and the output should be like langKeys.
How to do that?
This is array one:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
This is array two:
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
This is the output I need:
var langKeys = {
'en-*': 'en_US',
'es-*': 'es_ES',
'pt-*': 'pt_PT',
'fr-*': 'fr_FR',
'de-*': 'de_DE',
'ja-*': 'ja_JP',
'it-*': 'it_IT',
'*': 'en_US'
};
You can use map() function on one array and create your objects
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var output = keys.map(function(obj,index){
var myobj = {};
myobj[commonKeys[index]] = obj;
return myobj;
});
console.log(output);
JavaScript is a very versatile language, so it is possible to do what you want in a number of ways. You could use a basic loop to iterate through the arrays, like this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
var i;
var currentKey;
var currentVal;
var result = {}
for (i = 0; i < keys.length; i++) {
currentKey = commonKeys[i];
currentVal = keys[i];
result[currentKey] = currentVal;
}
This example will work in all browsers.
ES6 update:
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT', 'en_US'];
let zipArrays = (keysArray, valuesArray) => Object.fromEntries(keysArray.map((value, index) => [value, valuesArray[index]]));
let langKeys = zipArrays(commonKeys, keys);
console.log(langKeys);
// let langKeys = Object.fromEntries(commonKeys.map((val, ind) => [val, keys[ind]]));
What you want to achieve is to create an object from two arrays. The first array contains the values and the second array contains the properties names of the object.
As in javascript you can create new properties with variales, e.g.
objectName[expression] = value; // x = "age"; person[x] = 18,
you can simply do this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var langKeys = {};
var i;
for (i=0; i < keys.length; i++) {
langKeys[commonKeys[i]] = keys[i];
}
EDIT
This will work only if both arrays have the same size (actually if keys is smaller or same size than commonKeys).
For the last element of langKeys in your example, you will have to add it manually after the loop.
What you wanted to achieve was maybe something more complicated, but then there is missing information in your question.
Try this may be it helps.
var langKeys = {};
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
function createArray(element, index, array) {
langKeys[element]= keys[index];
if(!keys[index]){
langKeys[element]= keys[index-(commonKeys.length-1)];
}
}
commonKeys.forEach(createArray);
console.info(langKeys);
Use a for loop to iterate through both of the arrays, and assign one to the other using array[i] where i is a variable representing the index position of the value.
var keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
var commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
var langKeys = {};
for (var i = 0; i < keys.length; i++) {
var commonkey = commonKeys[i];
langKeys[commonkey] = keys[i];
}
console.log(JSON.stringify(langKeys));
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
// declaration of empty object where we'll store the key:value
let result = {};
// iteration over first array to pick up the index number
for (let i in keys) {
// for educational purposes, showing the number stored in i (index)
console.log(`index number: ${i}`);
// filling the object with every element indicated by the index
// objects works in the basis of key:value so first position of the index(i)
// will be filled with the first position of the first array (keys) and the second array (commonKeys) and so on.
result[keys[i]] = commonKeys[i];
// keep in mind that for in will iterate through the whole array length
}
console.log(result);

Creating and Accessing 2-dimensional arrays in javascript

I'm confused about how to create and access 2-dimensional arrays in javascript. Below is an array declaration in which I'm storing names of people and then the src for their image. When I try to access myArray[0][0] element I get 'D' and when I try to access myArray[0,0], I get Donald Duck. How can I access the img src myArray[0][0] = "assets/scrybe.jpg" ?
JS code:
var myArray = new Array(1);
myArray[0] = "Donald Duck";
myArray[1] = "Winnie Pooh";
myArray[2] = "Komal Waseem";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
myArray[6] = "Mickey Mouse";
myArray[0][0] = "assets/scrybe.jpg";
myArray[1][0] = "assets/scrybe.jpg";
myArray[2][0] = "assets/scrybe.jpg";
myArray[3][0] = "assets/scrybe.jpg";
myArray[4][0] = "assets/scrybe.jpg";
myArray[5][0] = "assets/scrybe.jpg";
myArray[6][0] = "assets/scrybe.jpg";
Firstly, to create an array, it's better to use the square bracket notation ( [] ):
var myArray = [];
This is the way you emulate a multi-demensional array in JavaScript. It's one or more arrays inside an array.
var myArray = [
[], [] // two arrays
];
If you're asking if there's a way to declare an array as multi-dimensional, then no, there isn't. You can access them like this:
myArray[0][0]; // the 1st element of the first array in myArray
myArray[1][1]; // the 2nd element of the second array in myArray
Here is the code you were probably looking for:
var myArray = [
["Donald Duck", "assets/scrybe.jpg"],
["Winnie Pooh", "assets/scrybe.jpg"],
["Komal Waseem", "assets/scrybe.jpg"]
[/* and so on...*/]
];
But since you're giving all the names the same URL, then you can use a for loop instead to do this faster:
for (var i = 0; i < myArray.length; i++) {
myArray[i][1] = "assets/scrybe.jpg";
}
Perhaps what you really want is an array of objects:
var myArrray = [
{ name: "Donald Duck", image: "assets/scrybe.jpg" },
{ name: "Winnie Pooh", image: "assets/scrybe.jpg" },
// ...
];
JavaScript doesn't really have 2-dimensional arrays, as such. What you can do is create an array such that each element is also an array.
var twoDim = [ [], [], [], [], [] ];
In your case, however, I don't think that structure will help much.
No it cannot be done like that. Must either do:
var myArray = new Array(1);
myArray[0] = new Array(1);
myArray[0][0] = "Donald Duck";
myArray[0][1] = "assets/scrybe.jpg";
Or use JS syntax
var myJSObj = {"Donald" :"assets/scrybe.jpg", "Donald2": "assets/scrybe2.jpg" };
I had the same issues and I used minBy from Lodash
https://lodash.com/docs/4.17.4#minBy
var objects = [{ 'n': 1 }, { 'n': 2 }];
_.minBy(objects, function(o) { return o.n; });
// => { 'n': 1 }
// The `_.property` iteratee shorthand.
_.minBy(objects, 'n');
// => { 'n': 1 }

Push an associative item into an array in JavaScript

How can I correct the following code?
var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);
JSFiddle
To make something like associative array in JavaScript you have to use objects.
​
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
DEMO: http://jsfiddle.net/bz8pK/1/
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​
To get value you can use now different ways:
console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
They are simply called objects.
Another method for creating a JavaScript associative array
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.
// Order of entry altered
let obj = {}; // will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);
// Order of entry maintained for future iteration
obj = []; // will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);

Using split/join to replace a string with an array

I'm trying to replace the value of item with values ​​in the array arr, but I only get that if I use: arr [1], arr [2] ... if I just let
arr, returns abcdefg.
I am PHP programmer, and I have a minimal
notion with JavaScript, can someone give me a light?
var item = 'abcdefg';
var arr = new Array();
arr[1] = "zzz";
arr[2] = "abc";
var test = item.split(arr);
alert(test.join("\n"));
Use:
var item = 'Hello, 1, my name is 2.';
var arr = new Array();
arr [1] = 'admin';
arr [2] = 'guest';
for (var x in arr)
item = item.replace(x, arr[x]);
alert(item);
It produces:
Hello, admin, my name is guest.
Split uses regular expressions, so
"My String".split('S') == ["My ","tring"]
If you are trying to replace a string:
"abcdef".replace('abc','zzz') == "zzzdef"

Categories

Resources