I have certain data sets. Example, A,B and C. There are sets of these values. For example:-
[A:asd, B:ajs, C:aknd],
[A:sdf, B:gss, C:fdss],
[A:ijq, B:cba, C:jqwd]
etc.
Now i want to make a dictionary containing these values as separate dictionaries. For example:-
{
{
A:asd,
B:ajs,
C:aknd
},
{
A:sdf,
B:gss,
C:fdss
},
{
A:ijq,
B:cba,
C:jqwd
}
}
Can someone help me out with this.
I tried doing this but it's not making a dictionary.
for( var i=0; i< n; i++) {
data += {
"A":value1,
"B":value2,
"C":value3
}
}
Any inputs?
This does not make sense in Javascript:
{
{
A:asd,
B:ajs,
C:aknd
},
{
A:sdf,
B:gss,
C:fdss
},
{
A:ijq,
B:cba,
C:jqwd
}
}
If you intend to have an object (dictionary) with integer keys, you could do it like so:
var data = {};
for( var i=0; i< n; i++) {
data[i] = {
"A":value1,
"B":value2,
"C":value3
}
}
Depending a bit on what you're trying to do, an array would likely be a better choice:
var data = [];
for( var i=0; i< n; i++) {
data.push({
"A":value1,
"B":value2,
"C":value3
});
}
Related
I'd like to use an object to configure some settings for an app. My idea is to start with this:
var obj = {
property_one: 3;
property_two: 2;
property_three: 1;
}
And I would like to end up with this:
var array = [
'property_one','property_one','property_one',
'property_two','property_two',
'property_three'
]
My current solution is to do this for each property:
function theConstructor(){
for(i=1; i <= obj.property_one; i++){
this.array.push('property_one');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
}
But this gets tedious, because I might have many properties, and these might change as the app evolves.
I know I can loop through object's properties like this:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
array.push(key);
}
}
But this will push the value to the array, not the key (as a string). Any ideas about how I can do this more efficiently?
Try this
function theConstructor(){
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
for(var i=1; i <= obj[key]; i++){
this.array.push(key);
};
}
}
}
Using Array.prototype.reduce():
var obj = {
property_one: 3,
property_two: 2,
property_three: 1
};
var resultArray = Object.keys(obj).reduce(function(result, curItem) {
for (var index = 0; index < obj[curItem]; index++) {
result.push(curItem);
}
return result;
}, []);
document.write(JSON.stringify(resultArray));
I want to store array values in a js dictionary (for each date key, there is an array of objects for that date).
Is this possible? and if not, what is the best way to do so?
this is data (fetched from a json):
[
{
"date":"2015-02-08",
"hour":6,
"mac_address":"0C:3E:9F:60:53:32",
"is_inside":"0"
},
{
"date":"2015-02-08",
"hour":6,
"mac_address":"40:0E:85:52:68:4E",
"is_inside":"0"
},
{
"date":"2015-02-08",
"hour":6,
"mac_address":"60:F8:1D:DB:E4:A0",
"is_inside":"0"
}
]
I tried the following, but it just makes a long value of one string.
for (var i=0; i<data.length; i++){
usersByDay[data[i].date] += data[i];
}
What can I do to make a data structure like so:
{date: [object, object, object], another_date: [object...]}, i.e:
{"2015-02-08": [
{
"date":"2015-02-08",
"hour":6,
"mac_address":"0C:3E:9F:60:53:32",
"is_inside":"0" },
{
"date":"2015-02-08",
"hour":6,
"mac_address":"40:0E:85:52:68:4E",
"is_inside":"0" }]
}
+= doesn’t push values into an array in JavaScript, but push does! You’ll also need to check whether the key exists, and create a new array if it doesn’t.
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (usersByDay[item.date]) {
usersByDay[item.date].push(item);
} else {
usersByDay[item.date] = [item];
}
}
Or, if you like “fanciness”:
for (var i = 0; i < data.length; i++) {
var item = data[i];
(usersByDay[item.date] || (usersByDay[item.date] = [])).push(item);
}
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"));
I have the below javascript array with me
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15}
},
{
Science:{
ST1:50,
ST3:40}
}
]
I want to generate the array shown below out of this
var t = [{ST1:{
Maths:10,
Science:50
},
ST2:{
Maths:2,
Science:0
},
ST3:{
Maths:15,
Science:40
}
}]
I tried using the code shown below
for (var key in test) {
if (test.hasOwnProperty(key)) {
for (var key1 in test[key]){
//console.log(key1)}
var abc = test[key][key1];
for(var x in abc)
{
console.log(x+key1+abc[x])
}
}
}
}
I am new to this help me doing this.
This does mostly what you want...
var t = {};
for (var i = 0; i < test.length; i++) {
for (var name in test[i]) {
for (var level in test[i][name]) {
if (!t[level])
t[level] = {}
t[level][name] = test[i][name][level]
}
}
}
Only thing missing is to get the Science:0 for when a STx value is missing under a section.
DEMO: http://jsfiddle.net/eHwBC/
Result:
{
"ST1": {
"Maths": 10,
"Science": 50
},
"ST2": {
"Maths": 2
},
"ST3": {
"Maths": 15,
"Science": 40
}
}
Keep in mind that there's no guaranteed order when using for-in for enumeration.
If the labels (Math, Science, etc) are known in advance, then you can ensure that each object gets all labels.
If not, a separate loop can be done. Depending on the approach, it could be done before or after this main loop.
Do you know about JSON.stringify(t)?
It will convert an object literal to JSON.
Mozilla's documentation of this function is available at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.
You can also read this blog article for further explanation
Try this:
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15
}
},
{
Science:{
ST1:50,
ST3:40}
}
];
var result = [];
for(i = 0; i <= test.length; i++){
var resultRow = {};
for(key in test[i]){
for(subKey in test[i][key]){
if(resultRow[subKey] == undefined){
resultRow[subKey] = {};
}
resultRow[subKey][key] = test[i][key][subKey];
}
}
result.push(resultRow);
}
Try like below,
/* Iterator start */
var t = {};
for (var i = 0; i < test.length; i++) { //Iterate Maths, Science,..
for (var key in test[i]) { //Iterate Math
for (var iKey in test[i][key]) { //Iterate ST1, ST2, ST3
var s = (t.hasOwnProperty(iKey))?t[iKey]:createObject();
s[key] = test[i][key][iKey];
t[iKey] = s;
}
}
}
/* Iterator End */
p = [];
p.push(t);
//^- p is what you want
// Separate function so you can add more items later without changing logic
function createObject () {
return {'Maths' : 0, 'Science': 0};
}
DEMO and Proof below,
I am trying to create an object iteratively with the following structure:
var series = {
data: [{
name: 'some text',
y: 0
},
{
name: 'some other text',
y: 1
}]
}
Below is my code so far:
var series = {
data: []
};
var datatemp = {
y: '',
name: ''
};
for (var i=0; i<10; i++) {
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
But what I am getting is the final values of series.data[i].y and series.data[i].name in all elements of the array, rather than what I expect, which is different values as the counter i iterates. I would appreciate your guidance on what I am doing wrong. Thanks in advance!
To add to what Mimisbrunnr said, you could even do it this way:
for (var i=0; i<10; i++) {
series.data.push({y: i, name: "namelabel"+i});
}
There is no need for the intermediate variable.
You need to make a new datatemp for each iteration of the for loop otherwise you are just passing the same object into the array each time and modifying it's values.
for (var i=0; i<10; i++) {
var datatemp = {};
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
var series = {
data: []
};
for (var i=0; i<10; i++) {
var datatemp={};
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
for (var i=0; i<10; i++) {
console.log(series.data[i].y);
console.log(series.data[i].name);
}
http://jsfiddle.net/Vp8EV/
Objects are passed by reference in javascript, in your example you only have one object which is referenced by the name datatemp, every time you assign a new value to one of its members the old member gets overwritten, so you have to create a new object for each iteration of the loop.