How to optimize this kind of code - javascript

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}};

Related

Collect values from a spreadsheet, look for those values in a string and replace

The values in my spreadsheet are these:
/2021/
/20212022/
/2022/
/20222023/
/2023/
To try to find these values in a string and then replace with /####/ I tried creating a map:
var sheet = SpreadsheetApp.getActive().getSheetByName('One')
var liga = 'https://int.testestest.com/national/united-states/mls/2022/regular-season/r66725/'
var years = sheet.getRange('One!A10:A14').getValues().flat();
var mapObj = {one: years[0],two: years[1],three: years[2],four: years[3],five: years[4]};
var liga_substitute = liga.replace(/\b(?:one|two|three|four|five)\b/gi, matched => mapObj[matched]);
var liga_final_subs = liga_substitute.replace('one','/####/').replace('two','/####/').replace('three','/####/').replace('four','/####/').replace('five','/####/')
But the result after substitution remains the same:
https://int.testestest.com/national/united-states/mls/2022/regular-season/r66725/
My final expected result is:
https://int.testestest.com/national/united-states/mls/####/regular-season/r66725/
And in var liga_final_subs = exist the risk of finding these parts of text in the wrong places and replacing what shouldn't.
How should I go about doing this correctly?
Not sure what you trying to gain. Here is the code that does the job (I hope):
var liga = 'https://int.testestest.com/national/united-states/mls/2022/regular-season/r66725/'
var years = [
'/2021/',
'/20212022/',
'/2022/',
'/20222023/',
'/2023/',
];
var liga_final_subs = liga;
years.forEach(x => liga_final_subs = liga_final_subs.replace(x, '/####/'));
console.log(liga_final_subs);

AngularJS Convert Array to JSON

I have an array containing 3 elements
var a = [];
a["username"]=$scope.username;
a["phoneNo"]=$scope.phoneNo;
a["altPhoneNo"]=$scope.altPhoneNo;
Now, I want to send this data to server in JSON format. Therefore, I used
var aa = JSON.stringify(a);
console.log("aa = "+aa);
But the console displays empty array
aa = []
How can I convert this array into JSON?
That's not the correct way to add elements to an array, you're adding properties instead.
If you did console.log(a.username); you'd see your $scope.username value.
You could either do
var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});
But it looks more like what you're trying to do is
var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;
That is, you want your a to be an object if you're going to add properties to it.
And that would be better written as
var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;

Javascript, adding string to array[string]

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] }

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