Iterate over a JSON Array in JavaScript or jQuery - javascript

I need to loop over a JSON Array which comes from the server. It looks exactly like this:
[{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}]
I found some advices here, but none of them seem to work for me.. Is there any easy way to get all these values?

var arr = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}];
for(var i = 0; l = arr.length; i< l; i+=1)
{
console.log(arr[i].username); // log username
}
another option:
arr.forEach(function(i) {
console.log(i.username)
});

var data = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}],
usernames = [];
for(var i=0; i<data.length; i++) {
usernames.push(data[i].username);
}

try this:
var o = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}];
for(var i = 0; i < o.length ; i++)
for(var j in o[i])
alert(j + ": " + o[i][j]);

If you don't need IE<9 compatibility, you can use Array.prototype.map()
var arr = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}],
usernames = arr.map(function(item) {
return item.username;
});

Related

Alternately Join 2 strings - Javascript

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

Efficient way to turn a string to a 2d array in Javascript

I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.
function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < colCount; j++) {
var temp = rows[i].split(',');
if (!arr[i]) arr[i] = []
arr[i][j] = temp[j];
}
}
for (var i = 1; i < colCount; i++) {
for (var j = 1; j < rows.length; j++) {
verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
}
}
This would be a good candidate for Array.prototype.map
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})
What map does is iterate over an array and applies a projection function on each element returning a new array as the result.
You can visualize what is happening like this:
function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];

How to show a list or array into a tree structure in javascript?

I pass this list from python to javascript like this:
var string=["test_data/new_directory/ok.txt","test_data/reads_1.fq","test_data/test_ref.fa"];
I want output like this:
test_data
reads_1.fq
test_ref.fa
new_directory
ok.txt
Or also the output could be like this:
test_data
reads_1.fq
test_ref.fa
test_data/new_directory
ok.txt
I used split function to get a list with each file and directory like this:
var string=["test_data/new_directory/ok.txt","test_data/reads_1.fq","test_data/test_ref.fa"];
for(var i=0;i<string.length;i++){
var result = string[i].split('/');
console.log(result);
}
Output looks like this:
["test_data", "new_directory", "ok.txt"]
["test_data", "reads_1.fq"]
["test_data", "test_ref.fa"]
How can I convert into the format I showed above? Thanks
Sorry for being late to the party. I ran into a similar issue trying to break out a list of paths into a nested object. Here's a fiddle showing how I ended up doing it.
var list = [];
list.push("A/B/C");
list.push("A/B/D");
list.push("A/B/C");
list.push("B/D/E");
list.push("D/B/E");
list.push("A/D/C");
var data = [];
for(var i = 0 ; i< list.length; i++)
{
buildTree(list[i].split('/'),data);
}
debugger;
function buildTree(parts,treeNode) {
if(parts.length === 0)
{
return;
}
for(var i = 0 ; i < treeNode.length; i++)
{
if(parts[0] == treeNode[i].text)
{
buildTree(parts.splice(1,parts.length),treeNode[i].children);
return;
}
}
var newNode = {'text': parts[0] ,'children':[]};
treeNode.push(newNode);
buildTree(parts.splice(1,parts.length),newNode.children);
}
https://jsfiddle.net/z07q8omt/
That's certainly possible, but it requires recursion.
The first thing you'll want to do (as you've already figured out to do, in fact) is split on the slashes. We'll use map for simplicity:
paths = paths.map(function(path) { return path.split('/'); });
Now we'll want to convert this into an array of objects with name and children properties. This means we'll have to use recursion.
In this function, we'll do a first pass grouping them by their first element:
var items = [];
for(var i = 0, l = paths.length; i < l; i++) {
var path = paths[i];
var name = path[0];
var rest = path.slice(1);
var item = null;
for(var j = 0, m = items.length; j < m; j++) {
if(items[j].name === name) {
item = items[j];
break;
}
}
if(item === null) {
item = {name: name, children: []};
items.push(item);
}
if(rest.length > 0) {
item.children.push(rest);
}
}
Then we can recurse on all of these (assuming the function name we chose was structurize):
for(i = 0, l = items.length; i < l; i++) {
item = items[i];
item.children = structurize(item.children);
}
Now we've got a nice structure. We can then stringify it, again with a recursive function. Since the directory listing is just each item name followed by the indented directory contents listing, we can write that fairly easily:
function stringify(items) {
var lines = [];
for(var i = 0, l = items.length; i < l; i++) {
var item = items[i];
lines.push(item.name);
var subLines = stringify(item.children);
for(var j = 0, m = subLines.length; j < m; j++) {
lines.push(" " + subLines[j]);
}
}
return lines;
}
Then, to actually do it:
console.log(stringify(structurize(paths)).join("\n"));

Javascript, arrays [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Counting occurences of Javascript array elements
I have an array in javascript and for example the array is:
array(1,1,1,1,5,5,7,7);
If can some one please help me to understand how to count similar values,
And how to join similar values,
Thank you all and have a nice day.
var array = [1,1,1,1,5,5,7,7];
var count = 0;
var tempArray = array.sort();
var i;
var prevValue = null;
var joined = [];
for (i = 0; i < array.length; i++) {
if (tempArray[i] != prevValue) {
count++;
prevValue = tempArray[i];
joined.push(prevValue);
}
}
​document.write(joined);​
If you're looking to uniquely identify array contents:
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
var myArray = [1,1,1,1,5,5,7,7];
var uniquedMyArray = myArray.unique();
var valueCountsMyArray = [];
for (var i = 0; i < myArray.length; i++) {
if (valueCountsMyArray[myArray[i]])
valueCountsMyArray[myArray[i]]++;
else
valueCountsMyArray[myArray[i]] = 1;
}
I can suggest using underscore.js. The code you're looking for isn't hard to write, and would be a good learning experience. Once you've done that, underscore is fantastic convenience library that offers what you're looking for, and you don't have to maintain it. :)
The uniq function will give you a copy of your array without duplicates, and the size function will tell you how many values that contains (or just reference the .length property).
Here a solution to count how many time it contains a number.
var count = [];
for(var i=0; i<array.length; i++) {
count[array[i]]++;
}

Splitting to 2D array

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

Categories