I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source
Related
I am new to js.
I am trying to write a code which reverses null terminated string.
I tried writing using push and pop.
but i am not getting output, can you tell me what is the problem.
providing code below
var word = "Cell0";
//var char = word.stringCharAT();
for (i=0; i< word.length; i++) {
var pushWord = [];
pushWord.push(word[i]);
for (j=0; j< pushWord.length; j++) {
var reverseWord= [];
reverseWord = pushWord[j].pop;
console.log("reverseWord" + reverseWord);
}
}
Here's a solution.
var word = "Cell0";
var reversed = '';
for (var i = word.length-1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
This loops through the characters of the string in reverse and adds the characters to a new string.
pushWord[j] is not an array, .pop is not called.
Define pushWord and reverseWord arrays outside of for loop, within loop, after word[i] is pushed to pushWord, call .unshift() on reverseWord with pushWord[pushWord.length -1] as parameter.
var word = "Cell0";
var pushWord = [];
var reverseWord = [];
for (let i = 0; i < word.length; i++) {
pushWord.push(word[i]);
reverseWord.unshift(pushWord[pushWord.length - 1]);
}
console.log("reverseWord" + reverseWord);
var originalWord = "Cell0";
var reverseWord = [];
for (let i = 0; i < originalWord.length; i++) {
reverseWord.unshift(originalWord [i]);
}
console.log(reverseWord.join(''));
You don't even need to push.
Another way to achieve the result!
What I'm working on is a menu that auto updates its entries based on an array length. It adds groups of 10 objects' properties (in this case "IDnumbers") to the menu if a new object is added to the array.
var arraysOfObject = [], obj = {"IDNumber": ""};
for(i = 0; i<42; i++){
arraysOfObject.push({"IDNumber": "Number " + i});}
Above is the array holding 42 objects with a specific property.
var array2 = [];
var leftOver = arraysOfObject.length % 10;
var groupsOfTen = (arraysOfObject.length - leftOver)/10;
for (var i = 0; i < groupsOfTen; i++) {
array2.push([]);
for (var j = i*10; j < i*10 + 10; j++)
array2[i].push(arraysOfObject[j]["IDNumber"]);
}
//now the leftover
if (leftOver > 0) {
array2.push([]);
for (var i = groupsOfTen*10; i < arraysOfObject.length; i++)
array2[array2.length-1].push(arraysOfObject[i]["IDNumber"]);
}
The array2 above is the array that stores all the possible arrays that can be grouped by 10 from arraysOfObject. In this case there are 5 inside of it, because 4 arrays holds 40 objects, and 1 array holds the 2 remainders.
That all works fine, but placing the array2 inside the menu displays all possible IDnumbers grouped together, but not grouped individually. I have to declare each possible array inside of it like so sets = [array2[0], array2[1], array2[2], array2[3], array2[4]]; If there's a 6th possible array because object #51 has been added to arraysOfObject, I have to input it with array2[5].
I don't want it to depend on my input, but that it knows the number of possible arrays and that it displays it automatically in sets. How do I do that?
var gui = new dat.GUI();
var guiData = function() {
this.message = "Dat.Gui menu";
this.system = 0;
this.Sets = 0;
};
var data = new guiData();
sets = [array2[0], array2[1], array2[2], array2[3], array2[4], array2[5]];
gui.add(data, 'message', 'Dat.Gui Menu!');
gui.add(data, 'system', {
"1": 0,
"2": 1,
"3": 2,
"4": 3,
"5": 4,
"6": 5,
}).name('system #').onChange(function(value) {
updateSets(value);
});
gui.add(data, 'Sets', sets[0]).onChange();
function updateSets(id) {
var controller = gui.__controllers[2];
controller.remove();
gui.add(data, 'Sets', sets[id]).onChange();
data.Sets = 0;
gui.__controllers[2].updateDisplay();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.1/dat.gui.min.js"></script>
<script>
var arraysOfObject = [], obj = {"IDNumber": ""};
for(i = 0; i<42; i++){
arraysOfObject.push({"IDNumber": "Number " + i});}
var array2 = [];
var leftOver = arraysOfObject.length % 10;
var groupsOfTen = (arraysOfObject.length - leftOver)/10;
for (var i = 0; i < groupsOfTen; i++) {
array2.push([]);
for (var j = i*10; j < i*10 + 10; j++)
array2[i].push(arraysOfObject[j]["IDNumber"]);
}
//now take care of the leftover
if (leftOver > 0) {
array2.push([]);
for (var i = groupsOfTen*10; i < arraysOfObject.length; i++)
array2[array2.length-1].push(arraysOfObject[i]["IDNumber"]);
}
</script>
Not the issue at hand, but I was playing around with the dat.gui as you posted it and was wondering if the dropdown could be refilled without removing/adding/etc. It seems to work with .options. (NB The initialization code makes heavy use of ES6, but can work without. The system menu is created dynamically from the sets array)
let arraysOfObject =Array.from({length:42}, (o,i) => "Number " + i),
ch =10, sets = Array.from({length:Math.ceil(arraysOfObject.length/ch)}, (a,i) => arraysOfObject.slice(i*=ch, i+ch));
var gui = new dat.GUI();
var guiData = function() {
this.message = "Dat.Gui menu";
this.system = 0;
this.Sets = 0;
};
var data = new guiData();
gui.add(data, 'message', 'Dat.Gui Menu!');
gui.add(data, 'system', sets.reduce((obj,s,i) => (obj[i+1] = i, obj), {})).name('system #').onChange(updateSets);
let controller = gui.add(data, 'Sets');
updateSets(0);
function updateSets(id) {
controller = controller.options(sets[data.Sets = id]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.1/dat.gui.min.js"></script>
I think the easiest solution would be to use ES2015's spread operator which I don't know if you would want to use yet...
ES2015 method (demo)
sets = [...array2];
There are a few other changes in the demo to set the system variable
But after taking a closer look, you can optimize the code by using the method from this SO answer to chunk your array using slice(). Also, I'm not sure why an object was used to create array entries when it just ends up as a string... demo
var arraysOfObject = [],
system = {},
chunk = 10,
size = 92;
for (var i = 0; i < size; i++) {
arraysOfObject.push("Number " + i);
}
var sets = [];
var index = 0;
for (i = 0; i < size; i += chunk) {
sets.push(arraysOfObject.slice(i, i + chunk));
system[index + 1] = index++;
}
var gui = new dat.GUI();
var guiData = function() {
this.message = "Dat.Gui menu";
this.system = 0;
this.Sets = 0;
};
var data = new guiData();
gui.add(data, 'message', 'Dat.Gui Menu!');
gui
.add(data, 'system', system)
.name('system #')
.onChange(function(value) {
updateSets(value);
});
gui.add(data, 'Sets', sets[0]).onChange();
function updateSets(id) {
var controller = gui.__controllers[2];
controller.remove();
gui.add(data, 'Sets', sets[id]).onChange();
data.Sets = 0;
gui.__controllers[2].updateDisplay();
}
I tried to define a 3D array on Google Sheet, but even though I'm using the .slice() method it keeps passing the array by reference.
var temp = [];
for (var a = 0; a<archetypesAll.length; a++) {temp[a] = [0, a].slice();};
var archRank = [];
for (var a = 0; a<21; a++) {archRank[a]= temp.slice();};
archRank[2][1][0] = 'Test';
I want to edit a single element of the matrix but instead the code above just fills every row with the exact same value ('Test'):
3DMatrix[x][1][0] = 'Test'
You can't just copy a multidimensional array by calling slice at the top level, because that will not deep-copy the whole. You have to write your own deepCopy methid, like this:
function allocate(mainDim, ...dims) {
const result = new Array(mainDim);
for (let i = 0; i < result.length; i++) {
result[i] = dims.length > 0 ? allocate(...dims) : 0;
}
return result;
}
function deepCopy(matrix, dims) {
return dims > 1 ? matrix.map(row => deepCopy(row, dims - 1)) : matrix.slice();
}
function test() {
const mx1 = allocate(3,2,2);
mx1[2][1][0] = "Test";
console.log(JSON.stringify(mx1));
const mx2 = deepCopy(mx1, 3);
mx2[2][1][0] = "Copied";
console.log(JSON.stringify(mx1));
console.log(JSON.stringify(mx2));
}
test();
var array = ["Test", "Test"];
var array3d = [[array.slice(0)],[[array.slice(0)]]];
array3d[0][0][0] = "Changed";
console.log(JSON.stringify(array3d)); //[[["Changed","Test"]],[[["Test","Test"]]]]
Try with this instead of slice to get a new array instead of reference:
var temp = [];
for (var a = 0; a < archetypesAll.length; a++) {
temp[a] = JSON.parse(JSON.stringify([0, a]));
}
var archRank = [];
for (var a = 0; a < 21; a++) {
archRank[a]= temp.slice();
}
archRank[2][1][0] = 'Test';
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 I can split a string into 2D array. String is like
1c2c3r4c5c6r6c8c9
array should be like
[[1,2,3],
[4,5,6],
[7,8,9]]
var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/);
for (var i = 0; i < rows.length; i++)
rows[i] = rows[i].split(/c/);
Please note that I didn't test this so it might contain a syntax error or something...
You can use the map method on Array
var s = "1c2c3r4c5c6r6c8c9";
var rows = s.split("r");
result = rows.map(function (x) {
return x.split('c');
}));
map is introduced in ECMAScript5 and is not supported in older browsers. But, there is a decent work-around here
var str = "1c2c3r4c5c6r6c8c9";
var result = [];
var group = str.split("r");
for(i in group) {result.push(group[i].split("c"))};
result should be what you want.
This should work:
var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/g);
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(/c/g);
for (var j = 0; j < cells.length; j++) {
cells[j] = parseInt(cells[j]);
}
rows[i] = cells;
}