Javascript: Split array of arrays into multiple arrays - javascript

serious problem here, I have an array like this:
[[0,50],[0,68],[1,26],[2,9],[2,32]]
The form I need is to split this array into two separated arrays like this:
array1 = [[0,50][1,0][2,9]]
array2 = [[0,68][1,26][2,32]]
Yeah you are right guys, I need that to build flot chart.
If anybody interested in source of data this is how it looks in firebase:
{
"1433203200000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 50
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 68
}
},
"1433289600000" : {
"-JqsQjFTjHpzKqWgE_KJ" : {
"name" : "Samin Place",
"newVisitors" : 1,
"returningVisitors" : 25,
"totalVisitors" : 26
}
},
"1433376000000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 9
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 32
}
}
}
The point is loop each timestamp and each child, there we have totalVisitors that's the value I need for my chart.
BONUS
As you can see first timestamp have two childs thats fine, but second timestamp have only one child - "-JqsQjFTjHpzKqWgE_KJ" so I need to add null value for missing one into new array (in our example it's array1 second position).
That's what I'm calling CHALLENGE :)
Any help is very appreciated, thanks for attention.
Edit:
maybe if it can help to someone this is chart which I need
here is link
X-axis - are timestamps
Y-axis - totalVisitors value
Lines - every unique timestamp child

I created jsfiddle for you. Please tell, is it what you need?
http://jsfiddle.net/1vdryy3L/1/
// first, we'll get all possible keys ('key' is e.g. "-JpgJnANTpQFprRieImv")
var keys = [];
for (var i in data) {
for (var j in data[i]) {
if (keys.indexOf(j) == -1) {
keys.push(j);
}
}
}
var result = {}, tmp, k;
for (i in keys) {
tmp = []; k = 0;
for (var j in data) {
if (data[j][keys[i]]) {
tmp.push([k, data[j][keys[i]].totalVisitors]);
} else {
tmp.push([k, 0]);
}
k++;
}
result['array' + i] = tmp;
}
console.log(JSON.stringify(result));

Something like this should work provided that you are using jQuery. If you are not simply replace the jquery statements with standard js ones. (I have prepared a jsfiddle: jsfiddle:
var first = []
var second = [];
var my_data = {
"1433203200000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 50
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 68
}
},
"1433289600000" : {
"-JqsQjFTjHpzKqWgE_KJ" : {
"name" : "Samin Place",
"newVisitors" : 1,
"returningVisitors" : 25,
"totalVisitors" : 26
}
},
"1433376000000" : {
"-JpgJnANTpQFprRieImv" : {
"events" : 5,
"name" : "Home office",
"returningVisitors" : 9,
"totalVisitors" : 9
},
"-JqsQjFTjHpzKqWgE_KJ" : {
"events" : 10,
"name" : "Samin Place",
"returningVisitors" : 32,
"totalVisitors" : 32
}
}
}
var count = 0;
$.each(my_data, function(key, value){
if (value["-JpgJnANTpQFprRieImv"]){
first.push([count, value["-JpgJnANTpQFprRieImv"]["totalVisitors"]])
} else {
first.push([count, 0])
}
if (value["-JqsQjFTjHpzKqWgE_KJ"]){
second.push([count, value["-JqsQjFTjHpzKqWgE_KJ"]["totalVisitors"]])
} else {
second.push([count, 0])
}
count++;
});

Related

How to display all fields of a nested json in table format using Bootstrap

I want to write a utility which connects to a REST api downloads data in JSON format and then paints the data as nested tables using Bootstrap.
JSON Data -
[
{
"id" : "Id1",
"name" : "Name1",
"orders" : [{"orderId" : "o1", "size" : 34}, {"orderId" : "o2", "size" : 3}]
},
{
"id" : "Id2",
"name" : "Name2",
"orders" : [
{"orderId" : "o3", "size" : 5, "addresses" : [{"addressId" : "a1", "phone" : "1235"}, {"addressId" : "a2", "phone" : 555}]},
{"orderId" : "o4", "size" : 5, "addresses" : [{"addressId" : "a3", "phone" : "1235"}]}
]
}
]
I looked at the sub-table feature of Bootstrap, however it seems that it would need lot of custom code to get this working. Is there a better way to bind the json to table in a generic way?
Edit
After spending some time I was able to achieve this -
As you can see, I could get one level of nesting, however i just need to go one level deep. Any suggestions?
<script>
var $table = $('#table')
function buildTable($el, jsonData) {
var i; var j; var row
var columns = []
var data = []
if(!Array.isArray(jsonData) && jsonData.length == 0) {
return;
}
Object.keys(jsonData[0]).forEach( (k) => {
columns.push({
field: k,
title: k,
sortable: true
})
})
for(var j = 0; j < jsonData.length; j++) {
row = {}
Object.keys(jsonData[j]).forEach( (k) => {
row[k] = jsonData[j][k]
})
data.push(row)
}
$el.bootstrapTable({
columns: columns,
data: data,
detailFilter: function (index, row) {
console.log("detail filter " + Object.values(row))
for(var k in row) {
if(Array.isArray(row[k])){
return true;
}
}
return false;
},
onExpandRow: function (index, row, $detail) {
console.log("expand row keys " + Object.keys(row))
console.log("expand row vals " + Object.values(row))
var newRow = {};
for(var k in row) {
if(Array.isArray(row[k])){
alert('found ' + row[k])
newRow = row[k]
break
}
}
buildTable($detail.html('<table></table>').find('table'), newRow)
}
})
};
var mydata =
[
{
"id": 0,
"name": "test0",
"price": "$0",
"orders" :
[
{
"name" : "ABC",
"size" : 25,
"someList": [{"a":1, "b":2}, {"a":3, "b":4}]
},
{
"name" : "XYZ",
"size" : 50
}
]
}
/* {
"id": 1,
"name": "test1",
"price": "$1"
},
{
"id": 2,
"name": "test2",
"price": "$2",
"orders" : [{"name" : "def", "size": 45}]
}*/
];
$(function() {
buildTable($table, mydata)
})

Read data from arrays in javascript

I'm trying to read data from an array in JSON with javascript but I can't get it working. This is the segment of the JSON file from wich I want to read the data, I want to read the age variable from different arrays:
{
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" :
[
{
"result" :
{
duration : 0.97834,
empty : false,
suites :
[
cases :
[
{
"age" : 0,
"status" : Passed
}
{
"age" : 15,
"status" : Passed
}
{
"age" : 3,
"status" : failed
}
]
]
}
}
]
}
I've tried this:
for (var i = 0; i < jsonData.childReports.suites.cases.length; i++)
{
var age = jsonData.childReports.suites.cases[i];
}
But it doesn't work. What would be the best way to do this?
Thanks in advance,
Matthijs.
Try the following code:
for (var i = 0; i < jsonData.childReports[0].result.suites[0].cases.length; i++) {
var age = jsonData.childReports[0].result.suites[0].cases[i].age;
}
Correct Json:
{
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" : [
{
"result" : {
duration : 0.97834,
empty : false,
suites : [{
cases : [
{
"age" : 0,
"status" : "Passed"
},
{
"age" : 15,
"status" : "Passed"
},
{
"age" : 3,
"status" : "failed"
}
]}
]
}
}]
}
This way you can achieve that :
var data = {
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" : [
{
"result" : {
duration : 0.97834,
empty : false,
suites : [{
cases : [
{
"age" : 0,
"status" : "Passed"
},
{
"age" : 15,
"status" : "Passed"
},
{
"age" : 3,
"status" : "failed"
}
]}
]
}
}]
};
for (var i = 0; i < data.childReports[0].result.suites[0].cases.length; i++) {
console.log(data.childReports[0].result.suites[0].cases[i].age);
}
DEMO

MongoDB Shell: How to Update a Collection from a Collection

I have two collections: links and children.
Links has values like this:
> db.links.find().pretty()
{ "_id" : ObjectId("567374999df36aeeda6f2a5f"), "EID" : 1, "CID" : 1 }
{ "_id" : ObjectId("567374999df36aeeda6f2a60"), "EID" : 1, "CID" : 3 }
{ "_id" : ObjectId("567374999df36aeeda6f2a61"), "EID" : 2, "CID" : 5 }
Children has values like this:
{
"_id" : ObjectId("567382709df36aeeda6f2a7e"),
"CID" : 2,
"Cname" : "Mo",
"Age" : 11
}
{
"_id" : ObjectId("567382709df36aeeda6f2a7f"),
"CID" : 3,
"Cname" : "Adam",
"Age" : 13
}
{
"_id" : ObjectId("567382709df36aeeda6f2a80"),
"CID" : 4,
"Cname" : "Eve",
"Age" : 21
}
It seems like this should add EID to children where CID matches between links and children, but it does nothing.
db.children.find().forEach(function (doc1) {
var doc2 = db.links.find({ id: doc1.CID });
if (doc2.CID == doc1.CID) {
doc1.EID = doc2.EID;
db.children.save(doc1);
}
});
This sets the value of EID in children to the value of EID from links where the value of CID in children == 14.
db.children.find().forEach(function (doc1) {
var doc2 = db.links.find({},{_id: 0, CID: 1});
if (doc1.CID == 14) {
doc1.EID = doc1.CID;
db.children.save(doc1);
}
});
{
"_id" : ObjectId("567382709df36aeeda6f2a8a"),
"CID" : 14,
"Cname" : "George II",
"Age" : 12,
"EID" : 14
}
So, it seems like that the equality operation in Javascript (doc2.CID == doc1.CID) isn't working. Why won't this work? I assume I have the syntax wrong or am using the wrong equality operation or operator?
var doc2 = db.links.find({ id: doc1.CID });
doc2 here is a cursor, not the document itself. So you need to go through documents in the cursor.
Try the following code:
db.children.find().forEach(function (doc1) {
var doc2 = db.links.find({CID:doc1.CID}).forEach(function(doc2){
doc1.EID = doc2.EID;
db.children.save(doc1);
})
})

object transformation with underscore.js

For whatever reason, I have quite a bit of difficulty when trying to transform objects and arrays.
The current data I have is stored in a mongodb collection and looks like this:
[{ "_id" : 1, "name" : "someName", "colorName" : "Pink"},
{ "_id" : 2, "name" : "someName2", "colorName" : "RoyalBlue"},
{ "_id" : 3, "name" : "aThirdOne", "colorName" : "Gold"},
{ "_id" : 4, "name" : "oneMore", "colorName" : "LightGreen"}]
I need to get either the following two arrays, but would like to know how to get both.
[{ "value" : 1, "label" : "someName"},
{ "value" : 2, "label" : "someName2"},
{ "value" : 3, "label" : "aThirdOne"},
{ "value" : 4, "label" : "oneMore"]
[{1 : "someName"},
{2 : "someName2"},
{3 : "aThirdOne"},
{4 : "oneMore"}]
I know it is probably something with _.map, but I am not sure why I can't figure it out. Please advise.
You don't really need Underscore for this, it's just normal Array.prototype.map method usage (although Underscore also provides this method):
var data = [{ "_id" : 1, "name" : "someName", "colorName" : "Pink"},
{ "_id" : 2, "name" : "someName2", "colorName" : "RoyalBlue"},
{ "_id" : 3, "name" : "aThirdOne", "colorName" : "Gold"},
{ "_id" : 4, "name" : "oneMore", "colorName" : "LightGreen"}];
var result = data.map(function(el, i) {
return {value: el._id, label: el.name};
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>';
Also note, that your second data structure doesn't make sense because it's irregular, so don't use it, it's not very convenient at all.
And here is corresponding Underscore version:
// Or Underscore version
var result = _.map(data, function(el) {
return {value: el._id, label: el.name};
});
In plain Javascript you can use Array.prototype.forEach() for iteration througt the array and assembling the objects and push it to the wanted results.
The forEach() method executes a provided function once per array element.
var array = [{ "_id": 1, "name": "someName", "colorName": "Pink" }, { "_id": 2, "name": "someName2", "colorName": "RoyalBlue" }, { "_id": 3, "name": "aThirdOne", "colorName": "Gold" }, { "_id": 4, "name": "oneMore", "colorName": "LightGreen" }],
result1 = [],
result2 = [];
array.forEach(function (a) {
result1.push({ value: a._id, label: a.name });
var o = {};
o[a._id] = a.name
result2.push(o);
});
document.write('<pre>' + JSON.stringify(result1, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(result2, 0, 4) + '</pre>');
use:
var newObject = _.map(yourObject, function(val) {
return {
"value": val._id,
"label": val.name
}});
And the same concept for the other result you're interested in .

mongodb update on JSON array

I have this data in Mongo:
{'_id':1,
'name':'Root',
'taskId':1,
'parentId':"",
'path':[1],
'tasks':[ {"taskId":3,parentId:1,name:'A',type:'task'},
{"taskId":4,parentId:1,name:'D',type:'task'},
{"taskId":5,parentId:4,name:'B',type:'task'},
{'type':'project' , 'proRef':2},
{"taskId":6,parentId:3,name:'E',type:'task'},
{"taskId":7,parentId:6,name:'C',type:'task'}]
}
Now I want to update taskId 6 with new Json data .
var jsonData = {"taskId":6,"name":'Sumeet','newField1':'Val1','newField2':'Val2'}
query should update if field is available else add new key to existing .Output Like
{"taskId":6,parentId:3,name:'Sumeet',type:'task','newField1':'Val1','newField2':'Val2'}]
I have tried few query but it is completely replacing json .
db.projectPlan.update({_id:1,'tasks.taskId':6},{$set :{'tasks.$':jsonData }});
Thanks in advance for your helps!
Sumeet
You need to transform the jsonData variable into something that can be passed to update. Here's an example that does exactly what you want with your sample document:
var updateData = {};
for (f in jsonData) {
if (f != "taskId") updateData["tasks.$."+f]=jsonData[f];
};
db.projectPlan.update({_id:1, 'tasks.taskId':6}, {$set:updateData})
Result:
{ "_id" : 1,
"name" : "Root",
"taskId" : 1,
"parentId" : "",
"path" : [ 1 ],
"tasks" : [
{ "taskId" : 3, "parentId" : 1, "name" : "A", "type" : "task" },
{ "taskId" : 4, "parentId" : 1, "name" : "D", "type" : "task" },
{ "taskId" : 5, "parentId" : 4, "name" : "B", "type" : "task" },
{ "type" : "project", "proRef" : 2 },
{ "taskId" : 6, "parentId" : 3, "name" : "Sumeet", "type" : "task", "newField1" : "Val1", "newField2" : "Val2" },
{ "taskId" : 7, "parentId" : 6, "name" : "C", "type" : "task" }
] }
You will need to merge the document manually:
var jsonData = {"taskId":5,"name":'Sumeet','newField1':'Val1','newField2':'Val2'};
db.projectPlan.find({ _id: 1 }).forEach(
function(entry) {
for (var taskKey in entry.tasks) {
if (entry.tasks[taskKey].taskId === jsonData.taskId) {
printjson(entry.tasks[taskKey]);
for (var taskSubKey in jsonData) {
entry.tasks[taskKey][taskSubKey] = jsonData[taskSubKey];
}
printjson(entry.tasks[taskKey]);
}
}
db.projectPlan.save(entry);
}
);
Obviously you can leave away the printjson statements. This is simply to see that the merging of the original tasks with the new tasks works. Note that this query will only update a single document as long as the _id field is unique.

Categories

Resources