Javascript, adding string to array[string] - javascript

I have two variables:
var cost = new Array();
var maxslot = new Array();
and I set the values like this:
<script>
cost = {"m2mp":"0.05"};
maxslot = {"m2mp":"1000"};
</script>
<script>
cost = {"samp":"0.04"};
maxslot = {"samp":"500"};
</script>
But samp replaces m2mp and if I call alert(cost["m2mp"]), it outputs undefined (if I don't assign samp, I get the correct output). I tried replacing = with +=, but it did not help (samp and m2mp are both undefined then).
I couldn't find any solution to "simulate" this:
cost["string"] = string;

Just do this:
<script>
cost["m2mp"] = "0.05";
maxslot["m2mp"] = "1000";
cost["samp"] = "0.04";
maxslot["samp"] = "500";
</script>
However, the way you want your variables makes them Objects, not Arrays. So you'll have to replace:
var cost = new Array();
var maxslot = new Array();
With:
var cost = new Object();
var maxslot = new Object();
Or, you could just declare the variables and assign values to it in one line, in a "Object literal":
var cost = {'m2mp':'0.05', 'samp': '0.04'}
var maxslot = {'m2mp':'1000', 'samp': '500'}

In your second snippet you're creating objects (curly braces), not arrays. Are you trying to add key-value pairs to your vars?
You should simply set the properties you need:
var cost, maxslot;
// ...
cost = {"m2mp":"0.05"};
maxslot = {"m2mp":"1000"};
cost["samp"] = "0.04";
maxslot["samp"] = "500";
In JavaScript you create a new object using curly braces:
var obj = {};
obj.constructor; // function Object() { [native code] }
Side note: [] notation is preferred over new Array() when creating an array.
var arr = [];
arr.constructor; // function Array() { [native code] }

Related

How to optimize this kind of code

How could i get the mark and mary by using searchstring and current_object? I have to use array_push for pushing new searchstring and current_object for create new output like mark and mary.
function get_suggestion_array_from_object(searchstring, current_object) {
var suggestion_array = [];
console.log(current_object);
}
var test_searchstring = 'Ma';
var test_current_object_string = '{"r":{"k":0,"y":0}}';
var test_current_object = JSON.parse(test_current_object_string);
get_suggestion_array_from_object(test_searchstring, test_current_object);
I'm not sure at all what it is you're asking but just a simple optimization would be this:
instead of writing a JSON string and then parsing it to an object, write the object immediatly:
var test_current_object_string = '{"r":{"k":0,"y":0}}';
var test_current_object = JSON.parse(test_current_object_string);
into:
var test_current_object = {r:{k:0, y:0}};

How can i create object once we have values?

I am new to javascript so i dont know how to create object once we have values dynamically , so below code i have fullName and workerKey from dataItem now i want to create object selectedOwners with values of fullName and workerKey.
How can i achieve that task ?
ctrl.js
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
var fullName = dataItem.fullName;
var workerKey = dataItem.workerKey;
console.log('WORKER KEY', workerKey);
}
You use an object initializer:
selectedOwners = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
};
The object initializer is the {...} bit. Each of those two things inside it is a property initializer. The part before the : is the name, the part after is the value, which can be the result of any expression.
In your code, you'd already created the object (var selectedItem = {};). The code above will replace that object. If you just wanted to add to it, you'd just use assignment:
selectedItem.fullName = dataItem.fullName;
selectedItem.workerKey = dataItem.workerKey;
Which you use depends on whether it matters that you not create a new object.
Edited, as per comments:
var list = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwners = {"fullname":dataItem.fullName,"workerKey":dataItem.workerKey};
list.push(selectedOwners);
}
// use list to populate output
You have already created the object so all you need to do is add the values into it.
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
selectedOwners.fullName = dataItem.fullName;
selectedOwners.workerKey = dataItem.workerKey;
//This will print out the newly populated object
console.log(selectedOwners);
}

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaƂ

javascript copying array to another

i have the following code snippet, where inside for loop the value to contain is not getting assigned, is this is the proper way to copy array to other.??
as here
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var m=grpNameArr.length;
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(m-1);ii++)
{
contain[ii] = groupCn[ii];
cmds[ii] = grpNameArr[ii];
}
If you want to clone an array you can use slice() method as mentioned in this page:
http://www.hardcode.nl/subcategory_1/article_414-copy-or-clone-javascript-array-object
var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
your array declaration is wrong , it should be like :-
var groupcn=["All","All","All","All"];
var grpNameArr=["abc","def","ghi"];
you can use :
var contain=groupcn.concat();
var cmds=grpNameArray.concat();
So, after your edit, I see your problem was that you has some typo's in your variable names.
Replace:
var grpNameArr = groupParm.split("#");
var groupcn= groupCondtn.split("&");
With:
var grpNameArr = groupParam.split("#");
// ^ Missing `a` and `r`.
var groupCn= groupCondition.split("&");
// ^ Capital C ^ Missing `i`'s and `o`.
Old Answer
These 2 lines:
var groupcn = All,All,All,All;
var grpNameArr = abc,def,ghi;
Are probably your problem.
What you're doing there is assigning the variable All to a new variable groupcn, then declaring All as a new variable, 3 times.
var groupcn=All,
All, // new variable with the name `All`
All, // new variable with the name `All`
All; // new variable with the name `All`. These 3 override `All`
You'll need to initialize them like this:
var groupcn = [All,All,All,All];
var grpNameArr = [abc,def,ghi];
Other than that, assuming m is the length of groupcn, the code should work.
However, a shorter solution is to copy the arrays like this:
var contain = groupcn.slice();
var cmds = grpNameArr.slice();
Following mistakes were in the code
Using one loop for both the arrays. Since there length is not same two different loops should be used.
There was typo mistake in groupcn variable.
Check this code
<!DOCTYPE html>
<html>
<script>
function chk()
{
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(groupcn.length-1);ii++)
contain[ii] = groupcn[ii];
for(ii=0;ii<(grpNameArr.length-1);ii++)
cmds[ii] = grpNameArr[ii];
alert("groupcn = "+contain);
alert("grpNameArr = "+cmds);
}
</script>
<body onload="chk()">
</body>

Is it possible to replace sub object with other object in main object?

I want to replace the sub object with some other object in main object.
ex:
var mianobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var newsubobj = {"n":"8888","g":"9999"}
console.log(mainobj.a.aa)
// this gives the sub object --> {"aaa":"0000","bbb":"1111"}
I want to replace this object with newsubobj.
I need the result as ::
console.log(mainobj);
// {"a":{"aa":{"n":"8888","g":"9999"}},"b":"222","c":"333"}
Thanks in advance.
Why you don't do it like that:
mainobj.a.aa = newsubobj
?
Ah, now we're getting somewhere. To update your question you have:
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"}
var subobjpath = "a.aa"; // this needs to be a string
var newsubobj = {"n":"8888","g":"9999"}
and you want to use subobjpath to replace a part of mainobj with newsubobj.
You can do so using code like this:
var path = subobjpath.split('.');
var obj = mainobj;
for(var idx=0; idx < path.length-1;idx++) obj = mainobj[path[idx]];
obj[path[path.length-1]] = newsubobj;
var mainobj = {"a":{"aa":{"aaa":"0000","bbb":"1111"}},"b":"222","c":"333"};
var newsubobj = {"n":"8888","g":"9999"};
mainobj.a.aa = newsubobj;
console.log(mainobj);

Categories

Resources