How to use hashmap in javascript - javascript

I have a hash map I want to use it in javascript. So I thought of converting it into javascript map..how to use it or to do?

Turn it into an object literal...
var map = {
'a' : 'a',
'b': 'b'
...
};

Or use Associative Arrays, for example:
var arr = new Array();
arr["One"] = 1;
arr["Two"] = 2;
arr["Thr"] = 3;
arr["For"] = 4;
for(var i in arr)
{
alert('Key='+i + ', Value = '+arr[i]);
}

Related

Create arrays inside array from string in JavaScript

I have strings like this :
"831,403,746,399,745,409,752,426,764,435,775,448,781,467,780,483,776,509,826,513"
"832,402,917,408,915,422,910,432,904,437,894,443,885,450,878,462,876,475,874,491,874,516,825,511"
"468,297.00000762939453,434,218.00000762939453,416,230.00000762939453,409,246.00000762939453,405,264.00000762939453,400,275.00000762939453,384,282.00000762939453,374,288.00000762939453,352,297.00000762939453,369,340.00000762939453"
... and so on.
I need to format the strings and produce arrays in array like this :
E.g.:
var myArray = [
[831,403],
[746,399],
[745,409],
[752,426],
[764,435],
[775,448],
[781,467],
[780,483],
[776,509],
[826,513],
];
It is possible and how?
Thanks in advance!
function parseToMatrix(str, rowCount = 2) {
let numbers_array = str.split(",").map((str) => parseFloat(str));
let matrix = [];
for (let i = 0; i < numbers_array.length; i += rowCount) {
matrix.push(numbers_array.slice(i, i + rowCount));
}
return matrix;
}
let str =
"831,403,746,399,745,409,752,426,764,435,775,448,781,467,780,483,776,509,826,513";
console.log(parseToMatrix(str));

how can i transmission array to object with lodash?

I have an array like as below
var arr = [ 'type=A', 'day=45' ];
var trans = { 'type': 'A', 'day': 45 }
Please write easiest and most efficient way :)
You could split the string and check if the value isNaN for string or take the numerical value.
var array = [ 'type=A', 'day=45', 'bar=0' ],
object = Object.create(null);
array.forEach(function (a) {
var p = a.split('=');
object[p[0]] = isNaN(p[1]) ? p[1] : +p[1];
});
console.log(object);
The solution using Array.prototype.reduce() function:
var arr = [ 'type=A', 'day=45' ],
trans = arr.reduce(function(r, s){
var parts = s.split('=');
r[parts[0]] = isNaN(parts[1]) ? parts[1] : +parts[1];
return r;
}, {});
console.log(trans);
Iterate over each item in the array
Split on =
Add value to object, at key index
var arr = [ 'type=A', 'day=45' ];
var object = {};
for (var i = 0; i < arr.length; i++) {
var currentItem = arr[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
There's probably a million different ways to this, this way uses two different functions. the _.map() call runs on every element, splitting (and parsing) the element (if it matches a character regex). It then uses Lodash's .fromPairs function, which converts an array made up of 2 element arrays to return an object.
var arr = ['type=A', 'day=45'];
var obj = _.fromPairs(_.map(arr, function(item) {
var parts = item.split('=');
var digits = /^\d+$/;
if (digits.test(parts[1])) parts[1] = parseInt(parts[1]);
return parts;
}));
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Javascript: In a loop, modify property of object then push to array

I have the following code (which works correctly):
var arr = [];
for(var i = 0; i < 2; i++) {
var obj = { a: 'A'};
obj.c = 'C' + i;
arr.push(obj);
}
// now arr is:
// [ {a: 'A', 'c': 'C0'}, {a: 'A', 'c': 'C1'} ]
To improve the performance of my code, I placed the obj outside the loop, then adding/modifying the new property only, like this:
var arr = [];
var obj = { a: 'A'};
for(var i = 0; i < 2; i++) {
obj.c = 'C' + i;
arr.push(obj);
}
// now arr is:
// [ {a: 'A', 'c': 'C1'}, {a: 'A', 'c': 'C1'} ]
Why both objects got C1 ? Please explain what I'm doing wrong, and how to place the object out of the loop and get correct results?
Note: I know this is a simple problem where performance is not an issue, but I'm actually dealing with big number of objects in reality where performance matters.
You are pushing the object (not a copy of the object) to the array, and then changing it.
If you want different objects in each index, then you need to create a new object each time you go around the loop.
Like the others wrote, you are changing the same object (the original) all the time which ends in the results being the same (the original).
To place the object out of the loop and still get the correct result, you would still have to 'copy' it inside of the loop:
var arr = [];
var obj = { a: 'A'};
var objstring = JSON.stringify(obj);
for(var i = 0; i < 2; i++) {
var obj = JSON.parse(objstring);
obj.c = 'C' + i;
arr.push(obj);
}

Converting a String to a Javascript Object

Am trying to convert the following string value into a javascript object
Example
string="name=usernamex&gender=boy&age=10&version_obj=1"
into
var user={ name:'username', gender:'boy',age:10,version_obj=1}
Can someone help me out
Looks like you want the querystring module: http://nodejs.org/api/querystring.html
querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
with pure javascript..
var str="name=usernamex&gender=boy&age=10&version_obj=1";
var array = str.split('&');
var obj = {};
array.forEach(function(value){
var x = value.split('=');
obj[x[0]] = decodeURIComponent(x[1]);
});
console.log(obj);
If you don't want to use a module:
var strArr = string.split("&");
var user = {}, i = 0, n;
while(i<strArr.length) {
n = strArr[i].split("=");
if(n.length == 2)
user[decodeURIComponent(n[0])]
= decodeURIComponent(n[1]);
i++;
}

How to verify containing values in hash tables without loop?

How to verify containing values in hash tables without loop in javascript?
For example:
var a = new Object(); // or just []
a[0] = 0
a['one'] = 1;
a['two'] = 2;
a['three'] = 3;
You can use hasOwnProperty
var hash = new Object(); // or just {}
hash['one'] = 1;
hash['two'] = 2;
hash['three'] = 3;
if (hash.hasOwnProperty(k)) {
alert('Has')
}
Try jQuery
$(hashtablename).each(function (item) {
//code to verify.
});
although internally it will prob still use a loop..

Categories

Resources