give name of a Variable from member of array - javascript

I want give name of an variable from member of an array like below ... but it show's SyntaxError: Parse error
var nemads=new Array("akhaber","mafakher");
var nemads[i] = new stocks(nemads[i],urls[i],"");
what i can do ?

Kind of, like this:
var nemads=new Array("akhaber","mafakher");
var arr = {};
for (var i = 0; i < nemads.length; ++i)
{
arr[nemads[i]] = "test" + i;
}
for (var i in arr)
{
var item = arr[i];
console.log(item);
}
console.log(arr["akhaber"]);
Output:
test0
test1
test0

you can go with eval() method also.
var arr = new Array("ab", "cd");
alert(arr[0]); //output is ab
eval("div" + arr[0] + " = new Array('12','34')"); //this created a new var named 'divab'
alert(divab); //output is 12,34

Related

pushing array of string with variables to an array inside a loop

Could someone help me on below code? How do I push an array with variables?
function theBeatlesPlay(musicians, instruments) {
var array = []
var i;
var m = ms[i];
var it = its[i];
var string = "`${m}` plays `${it}`";
for (i = 0; i < 4; i++) {
array.push(string)
}
return array
}
Thanks a lot in advance!
Most of what you did should be placed inside the for loop. Like this:
function theBeatlesPlay(musicians, instruments){
var array = [];
for(var i=0; i<musicians.length; i++){
var m = musicians[i];
var it = instruments[i];
var string = `${m} plays ${it}`;
array.push(string);
}
return array;
}
Also note the syntax for the template literal: the whole string is delimited by backticks, and you should not have those double quotes.
Instead of iteration to 4, use the actual length of the array.
function theBeatlesPlay(musicians, instruments){
var array = []
var i;
for(i=0; i<4; i++){
var m = ms[i];
var it = its[i];
var string = "`${m}` plays `${it}`";
array.push(string)
}
return array
}
yes It is pseudo-code and It's actually something like this;
var ms = ["a a", "b b", "c c"];
var its = ["d d", "e e", "f f"];
function funct(ms, its){
var array = []
var i =0;
for(i=0; i<4; i++){
var m = ms[i];
var it = its[i];
var string = "${m} plays ${it}";
array.push(string)
}
return array
}

JavaScript arrays declaration ways difference

This could be a pretty basic question, in JavaScript, what's difference between:
var userDetails = {};
var usersList = [];
I was reading an article which had following code:
function GetSampleUsersList() {
var userDetails = {};
var usersList = [];
for (var i = 1; i <= 3; i++) {
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails);
}
return JSON.stringify(usersList);
}
Thanks
This is a pretty basic question.
var o = {}
initializes an empty object. Then you assign its properties.
var a = []
initializes an empty array. You then add the newly created object to the array
a.push( o );
You are using for every iteration the same userDetails, because you overwrite just the properties and while you have pushed the same object, you have always the same content for every element in the array.
function GetSampleUsersList() {
var userDetails = {};
var usersList = [];
for (var i = 1; i <= 3; i++) {
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails);
}
return JSON.stringify(usersList);
}
console.log(GetSampleUsersList());
Better use a new empty object for every loop.
function GetSampleUsersList() {
var userDetails;
var usersList = [];
for (var i = 1; i <= 3; i++) {
userDetails = {}; // this is necessary
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails);
}
return JSON.stringify(usersList);
}
console.log(GetSampleUsersList());
function GetSampleUsersList() {
var userDetails = {}; //created an empty object userDetails
var usersList = []; //created an empty array userDetails
for (var i = 1; i <= 3; i++) { //looping to add property and value in object and for each iteration object is getting pushed into array at an index i.
userDetails["UserId"] = i;
userDetails["UserName"] = "User- " + i;
userDetails["Company"] = "Company- " + i;
usersList.push(userDetails); // pushing object {"UserId":i, "UserName":"User-i", "Company":"Company-i"} into array
}
return JSON.stringify(usersList); // Parsing the object into javascript string
}
var userDetails = {}; -- object notation in javascript
var usersList = []; is an array notation in javascript.
for more infomation refer here http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

How to separate the string into two categories in jstl?

i have a string as,
String value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
Now i need split the names and those values.
I am unable to identify what to do.
I need to print the values as
Output
---
-----------------------------
' Name ' value '
'------------'--------------'
' Bhavani ' 12 '
' Pallavi ' 13 '
' Charanya ' 14 '
' ' '
----------------------------'
I think it can be done in jstl level..
But can anyone help me how to split that string.
you can use str.replace to create an object:
strvalue = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14"
obj={};
strvalue.replace(/(\w+)<>(\w+)/g,function(_,m1,m2){
obj[m1]=m2
})
console.log(obj)
This should do it:
var str = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
str = str.split('<<>>')
for(var i = 0; i < str.length; i++) {
str[i] = str[i].split('<>');
}
alert(str.join("\n"));
first split with <<>>
than split wiht <>
so you will get array with Bhavani , 12 in two indexes.
its simple to show in any way on view.
Personally, I'd store the key-value pairs in an object:
var myObj = {};
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
var stringArray = string.split('<<>>');
for(i in stringArray){
var key = stringArray[i].split('<>')[0];
var value = stringArray[i].split('<>')[1];
myObj[key] = value;
}
console.log('My object looks like', myObj);
Here is my solution, you'll get an array of objects with a name and value inside each object:
let value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
let splittedString = value.split("<<>>");
let names = [];
splittedString.forEach(function(value) {
let splittedProps = value.split("<>");
names.push({
name: splittedProps[0],
value: splittedProps[1]
});
});
console.log(names);
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var strArr = str.split("<<>>");
var result = {};
for(var i in strArr){
var p = strArr[i].split("<>");
result[p[0]] = p[1];
}
console.log(result);
First split with <<>>
then split string with <>
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}`
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}
alert(string.join("\n"));
`
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var txt = str.split("<<>>").join("|").split("<>").join("|").split("|")
var object=[];
for (var i=0; i<txt.length;i=i+2){
object.push({Name:txt[i],Value:txt[i+1]});
}
console.log(object);

how can I parse json with multiple lines

I have the following JSON:
[{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}]
I need to extract all "phoneNumber" using a js function.
I'm testing from using html and my function is not so good:
function getNumbers(strJSON)
{
strJSON = "[{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557704\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557705\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557706\",\"returnCode\":\"0\"}]";
var len = strJSON.length;
var begin_index = strJSON.indexOf("returnCode") - 2;
var last_index = len - 1;
var string_toSplit = strJSON.substring(begin_index, last_index);
var string_splitted = string_toSplit.split("{");
var out="";
alert(strJSON);
alert("string_splitted");
alert(string_splitted);
for ( var i = 0; i < string_splitted.length; i++)
{
if (string_splitted[i].charAt(string_splitted[i].length - 1) === ",")
{
string_splitted[i] = string_splitted[i].slice(0, -1);
}
var json = "{" + string_splitted[i];
var obj = JSON.parse(json);
if (i == string_splitted.length)
{
out = out + obj.phoneNumber;
}
else
{
out = out + obj.phoneNumber + ",";
}
}
return out;
}
For modern browsers you can use the .map() method
var j = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phones = j.map(function(item){return item.phoneNumber});
Update
After seeing your code (do not try to manually split/parse the json string.. use the JSON.parse method) you should use
function getNumbers(strJSON)
{
var myJson = JSON.parse( strJSON );
return myJson.map(function( item ){ return item.phoneNumber}).join(',');
}
Update: An even better way:
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
return obj.map(x => x.phoneNumber).join(", ")
}
Original Post:
A straight forward method is to just iterate over every object in the array and take the values out individually.
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phoneNumbers = [];
for (var i = 0; i < info.length; i++)
{
phoneNumbers.push(info[i].phoneNumber);
}
console.log(phoneNumbers);
http://jsfiddle.net/hX69r/
UPDATE:
http://jsfiddle.net/hX69r/1/
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoString = JSON.stringify(info); //this just turns the object array 'info' into a string
var numbers = getNumbers(infoString);
console.log(numbers);
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
var phoneNumbers = [];
for (var i = 0; i < obj.length; i++)
{
phoneNumbers.push(obj[i].phoneNumber);
}
return phoneNumbers.join(", ");
}
Additional Update:
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoSingle = {"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"};
console.log(info.length); // prints 4; so you know it has the []
console.log(infoSingle.length); // prints undefined; so you know it doesn't have []
Do not try to re-invent the wheel.
There are many ways to parse JSON already:
Use JSON.parse.
Use jQuery.parseJSON

How to add one array data into multiple dynamic arrays

I have one array in javascript like
var arr = ["aa","bb","cc", "dd"];
and now I want to store these values into multiple arrays dynamically like
var arr1 = ["aa"];
var arr2 = ["bb"];
var arr3 = ["cc"];
var arr4 = ["dd"];
Here the as per the size of the "arr" array I need to create dynamic arrays to store those values. For example in "arr" I have 4 values then I need to create 4 dynamic arrays to store 4 values.
I dont have any idea how to achieve this any help?
The only way I can think of doing exactly what you are asking for is with eval. I don't suggest using it so I put together an object, which is close and preferred.
http://jsfiddle.net/P9SSA/1/
var myOneArray = ["a","b","c","d"];
var varPrefix = "arr";
var myObj = {};
for (var i = 1; i <= myOneArray.length; i++) {
eval(varPrefix + i + '=["' + myOneArray[i-1] + '"]');
myObj[varPrefix + i] = [myOneArray[i-1]];
}
document.write(arr1);
document.write("<br>");
document.write(myObj.arr3);
In global scope you can do:
arr.forEach( function( value, index ) {
window["arr"+(index+1)] = [value];
});
Inside arbitrary scope, this is only possible under non-strict eval:
var arr = ["aa","bb","cc", "dd"];
eval( arr.map( function( value,index) {
value = typeof value == "string" ? '"' + value + '"' : value;
return 'var arr'+(index+1)+' = ['+value+']';
}).join(";") + ";" );
Evaluates the following code:
var arr1 = ["aa"];
var arr2 = ["bb"];
var arr3 = ["cc"];
var arr4 = ["dd"];
forEach shim
map shim
var arrayOfArrays = [];
for (var i = 0; i < arr.length; i++) {
arrayOfArrays[i] = [];
arrayOfArrays[i].push(arr[i]);
}

Categories