Trace on nested objects couchdb update handler - javascript

i need to edit nested objects with unique key's! in couhdb document, but i can't do it.
my doc structure:
{
"_id":"20",
"_rev":"rev",
tasks": {
"20.t01": {
"name": "test",
"status": [],
"tasks": {
"20.t01t01": {
"status": [
],
"name": "name",
"tasks": {
"20.t01t01t01": {
"status": [],
"name": "name",
"tasks": {
"20.t01t01t01t01": {
"name": "name",
"status": [],
"tasks": {
}
}
}
}
}
}
}
}
}
}
I nedd to push some objects into status array's.
The update handler function:
"status": function(doc, req) {
var data = JSON.parse(req.body);
var value = data.value;
var path = data.path;
var message = 'set ' + path + ' status ' + value;
var pathar = path.split(".");
var level;
var body = doc;
var evalstr = "body.";
if (pathar[1].length > 2) {
level = (pathar[1].length) / 3;
for (var i = 1; i <= level - 1; i++) {
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1].substring(0, i * 3) + "\"].";
}
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1] + "\"].status.push(" + JSON.stringify(value) + ");";
} else {
level = 1;
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1] + "\"].status.push(" + JSON.stringify(value) + ");";
}
eval([evalstr]);
doc = body;
//doc.tasks["20.t01"].tasks["20.t01t01"].status.push(value);
return [doc, JSON.stringify({
reg: evalstr,
doc: body
})];
}
how i write the design document update function for this structure in couchdb?
Tanks!

Related

JSON parse variable result

I have a JSON which I query with xhr. The objects (person) contain a key-value pair called "serviceLevel" that I have to split.
When I stack this in a variable (services) and log it like this:
let main = document.getElementsByTagName('main');
getXHR("GET", './db/orga.json', (success) => {
format(success)
}, (error) => {
console.error(error)
});
function format() {
let people = arguments[0];
for (let i in people) {
let person = people[i];
let services = person.serviceLevel.split(".");
console.log(services);
console.log(person.serviceLevel.split("."));
let idCard = document.createElement('div');
idCard.id = person.firstName + person.familyName;
idCard.classList.add('person');
idCard.innerHTML = "<div class=\"item nom\"><span class=\"prenom\">" + person.firstName + "</span><span class=\"famille\">" + person.familyName + "</span></div>";
idCard.innerHTML += "<span class=\"job\">" + person.jobTitle_1 + "</span>";
idCard.innerHTML += "<span class=\"mail\"><a href=\"mailto:" + person.mail + "\">" + person.mail + "</span>";
idCard.innerHTML += "<span class=\"tel\"><a href=\"tel:" + person.phone_1 + "\">" + person.phone_1 + "</span>";
idCard.innerHTML += "<span class=\"tel\"><a href=\"tel:" + person.mobile + "\">" + person.mobile + "</span>";
for (let j in services) {
let serviceElement = document.getElementById(services[j]);
if (!serviceElement) {
let serviceElement = document.createElement('div');
serviceElement.id = services[j];
serviceElement.classList.add('n' + j, "service");
serviceElement.innerHTML = "<span class=\"title\">" + services[j] + "</span>";
if (j == 0) {
if (services[services.length - 1] = j) {
serviceElement.appendChild(idCard);
main[0].appendChild(serviceElement);
}
} else {
let parent = services[j - 1],
parentService = document.getElementById(parent);
if (services[services.length - 1] = j) {
serviceElement.appendChild(idCard);
}
parentService.appendChild(serviceElement);
}
} else {
serviceElement.appendChild(idCard);
}
}
}
}
const data = [{
"Tri": "blablablabla, CSMSI.SAFS, n, XXXX, YYYY",
"Department": "The best department",
"serviceLevel": "CSMSI.SAFS",
"organisationLevel": "blablablabla",
"rang": "n",
"familyName": "XXXX",
"firstName": "YYYY",
"jobTitle_2": "Directeur",
"jobTitle_1": "Directeur",
"phone_1": "nn nn nn nn nn",
"phone_2": "",
"mobile": "nn nn nn nn nn",
"mail": "xxxx.yyyy#zzzz.fr",
"location": "france"
}];
format(data);
The results are different:
(2) ["CSMSI", "SAFS"]
0: "CSMSI"
1: "SAFS"
length: 2
(2) ["CSMSI", "SAFS"]
0: "CSMSI"
1: "1"
length: 2
As we can see, content of "services" are good, but when I extend the tree, the value of the second key value is "1" ... which is a problem. Is there a way to change this?
when I use a for loop with "classical" (i = 0; i < people.length; i++), i don't have the problem....

Nested array recursion - NodeJS

I have a nested array containing children on a dynamic amount of levels, i want to generate a conditional tree based on this array.
An example of the array:
[
{
condition: 'conditionA',
children: [
{
condition: 'conditionA_1',
children: [
...
]
},
]
},
{
condition: 'conditionB',
children: [
...
]
}
]
I would like to generate a string that hold following conditional statement
if (conditionA) {
if (conditionA_1) {
...
}
} else if (conditionB) {
...
}
Does anybody have any ideas how to handle this properly?
Thanks in advance.
Without indentation:
Just map each node in the array to if(condition) { ... } (recursively), then join the resulting blocks with " else ":
function makeSource(arr) {
return arr.map(function(node) {
return "if (" + node.condition + ") { " + (node.children? makeSource(node.children): "") + " }";
}).join(" else ");
}
Demo:
function makeSource(arr) {
return arr.map(function(node) {
return "if (" + node.condition + ") { " + (node.children? makeSource(node.children): "") + " }";
}).join(" else ");
}
var array = [ { condition: 'conditionA', children: [ { condition: 'conditionA_1'} ] }, { condition: 'conditionB' } ];
var source = makeSource(array);
console.log(source);
With indentation:
To achieve the indentation we'll need a variable that holds the depth of the current block. Just repeat the space character before every line in the resulting string depending on the depth variable. Increate depth at each recursive call:
function makeSource(arr, depth = 0) {
return arr.map(function(node) {
var str = " ".repeat(depth * 2) + "if (" + node.condition + ") {\n";
if(node.children) {
str += makeSource(node.children, depth + 1);
} else {
str += " ".repeat((depth + 1) * 2); // unecessary, it just indents the empty line to where the code should be
}
return str + "\n" + " ".repeat(depth * 2) + "}";
}).join(" else ");
}
The * 2 parts represent the indentation number. If you want to indent by 4 spaces instead, then replace them with * 4.
Demo:
function makeSource(arr, depth = 0) {
return arr.map(function(node) {
var str = " ".repeat(depth * 2) + "if (" + node.condition + ") {\n";
if(node.children) {
str += makeSource(node.children, depth + 1);
} else {
str += " ".repeat((depth + 1) * 2);
}
return str + "\n" + " ".repeat(depth * 2) + "}";
}).join(" else ");
}
var array = [ { condition: 'conditionA', children: [ { condition: 'conditionA_1'} ] }, { condition: 'conditionB' } ];
var source = makeSource(array);
console.log(source);
const input = [
{
condition: 'conditionA',
children: [
{
condition: 'conditionA_1',
children: [
]
},
]
},
{
condition: 'conditionB',
children: [
]
}
]
const createSource = arr =>{
let source = "";
if(arr.length === 0){
return source;
}
arr.forEach((value,index) =>{
source+="if( "+value.condition+" ){";
if(value.children){
source+=createSource(value.children)
}
source+="}" + (index+1 < arr.length ? " else " : "");
})
return source;
}
console.log(createSource(input))

How do I get values from an array?

I have an array which is in the following format:
RBS: [ {
"RegExp": "",
"Type": ""
} ],
PAN: [ {
"RegExp": "Date",
"Type": "Date"
} ]
Now I want to pass the value PAN to a method and it should get the count of PAN length 1 and get PAN of regex values and type value. How can I do this? I formed an array like this: Name holds RBS and PAN:
var Regexp = [];
RegExpr.push(Name + ":" + Regexp);
function Check(test) {
//test will be RBS /PAN
}
var obj = {
RBS:[{"RegExp":"","Type":""}],
PAN:[{"RegExp":"Date","Type":"Date"}]
};
function getTypeAndValue( obj, value )
{
var output;
var keys = Object.keys( obj );
if ( obj [value ] )
{
output = obj[ value ][ 0 ];
}
return output;
}
var value = getTypeAndValue( obj, "PAN" );
if ( value )
{
console.log( "type is " + value.Type + " and RegExp is " + value.RegExp );
}
else
{
console.log( "this value doesn't exists" );
}
You mean something like this?
HTML
<div id="count"></div>
<div id="detail"></div>
JAVASCRIPT
var countEl = document.getElementById("count");
var detailEl = document.getElementById("detail");
function Check(test){
var count = test.length;
countEl.innerHTML = "Count: " + count;
detailEl.innerHTML = "";
for (var i = 0 ; i < count ; i++){
var values = test[i];
detailEl.innerHTML +=
"<br/>" + (i +1) + ":<br/>" +
"RegExp: " + values["RegExp"] + "<br/>" +
"Type: " + values["Type"] + "<br/>";
}
}
var Name = {
RBS: [ {
"RegExp": "",
"Type": ""
} ],
PAN: [ {
"RegExp": "Date",
"Type": "Date"
} ]
};
Check(Name.PAN);
DEMO
Here's a JSFiddle.

javascript convert JSON string to JSON object

I al using javascript and looping through the values of a submitted form and trying to build a son object out of the form values.
This is an example of the final object I need:
{
"DataObject": {
"user": { "-name": "username" },
"contentFile": {
"-filename": "Breaking_News",
"lock": { "-fileIsBeingEdited": "false" },
"content": {
"line": [
{
"-index": "1",
"-text": "this is the header"
},
{
"-index": "2",
"-text": "this is the first line"
},
{
"-index": "3",
"-text": "this is the second line"
}
]
}
}
}
}
So far i am adding all of this data to a string as that seems to be the only way i can insert the form values (the line array) into the middle of the object.
var jsonStr = '{'
+ 'iceteaDataObject: {'
+ 'user: {"-name": "hindsc52"},'
+ 'contentFile: {'
+ '"-filename": "Ticker",'
+ 'lock: { "-fileIsBeingEdited": "false" },'
+ 'content: {'
+ 'line: ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += "-index: " + i + ',';
jsonStr += "-text: " + elem[i].value;
jsonStr += '},'
}
}
jsonStr += ']}}}}';
console.log(JSON.parse(jsonData));
however when running this I get the error: unexpected token 'i'.
I have tried to use stringily but then just outputs the entire sting again.
You don't need or want JSON for this, just build the object:
// Sample data
var elem = [{
value: "one"
}, {
value: "two"
}];
// Build the object
var obj = {
"DataObject": {
"user": {
"-name": "username"
},
"contentFile": {
"-filename": "Breaking_News",
"lock": {
"-fileIsBeingEdited": "false"
},
"content": {
"line": []
}
}
}
};
var line = obj.DataObject.contentFile.content.line;
elem.forEach(function(entry, index) {
if (entry.value != '') {
line.push({
"-index": index,
"-text": entry.value
});
}
});
// Show result:
document.body.innerHTML =
"<pre>" +
JSON.stringify(obj, null, 2) +
"</pre>";
Side note: You don't check for blank strings like this:
if (!entry.value == '') { // <== Incorrect
You can use:
if (entry.value != '') {
or:
if (entry.value) {
You shouldn't build JSON like this, but use JSON.stringify() (see MDN doc) instead:
var myObject={foo:"bar"};
var myJSON=JSON.stringify(myObject);
console.log(myJSON); //echo {"foo":"bar"}
Here is an alternative way:
var json = {
iceteaDataObject: {
"-name": "hindsc52"
},
contentFile: {
"-filename": "Ticker",
lock: { "-fileIsBeingEdited": "false" },
content: {line: []}
}
}
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
json.contentFile.content.line.push({"-index": i,"-text": elem[i].value }
}
}
var jsonStr = JSON.stringify(json);
You need to put all your keys in quotes for this to work. As the others have pointed out though, you are not really supposed to do this.
If you still want to do it your way, try this:
var jsonStr = '{'
+ '"iceteaDataObject": {'
+ '"user": {"-name": "hindsc52"},'
+ '"contentFile": {'
+ '"-filename": "Ticker",'
+ '"lock": { "-fileIsBeingEdited": "false" },'
+ '"content": {'
+ '"line": ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += '"-index": ' + i + ',';
jsonStr += '"-text": ' + '"' + elem[i].value + '"';
jsonStr += '},'
}
}
jsonStr += ']}}}}';

Generate table, store values from json array

I need to create tables for each index in a given array, also i need to store those values so that my for loops sends them to the tables created.
JavaScript:
for (c=0; c < components_count.length; c++)
{
console.log(components_count[c]);
}
how can this be done?
Here is the full JS:
var index;
var data;
var parsed;
$(document).ready(function() {
$.get('policy.json', function(data){
index = data;
},"json");
});
function search(){
var movement_select = $("#movements").val();
var id = $("#idSubmit").val();
var refnr = index.refnr;
var index_movements = index.movements;
//console.log(movement_select);
//for loop to test which movement from dropdown list! Done!
for (m=0; m < index_movements.length; m++)
{
if (index_movements[m].date == movement_select)
{
movement_select = index_movements[m];
}
}
var movements = index.movements;
var movements_description = movement_select.description;
var movements_premium = movement_select.premium;
var movements_payer = movement_select.payer;
var movements_payer_id = movement_select.payer.personid;
var movements_payer_name = movement_select.payer.name;
var movements_payer_surname = movement_select.payer.surname;
var movements_payer_fullname = movements_payer_name + " " + movements_payer_surname;
var movements_owner = movement_select.owner;
var movements_owner_id = movement_select.owner.personid;
var movements_owner_name = movement_select.owner.name;
var movements_owner_surname = movement_select.owner.surname;
var movements_owner_fullname = movements_owner_name + " " + movements_owner_surname;
var components_count = movement_select.components;
for (c=0; c < components_count.length; c++)
{
console.log(components_count[c]);
}
var components = movement_select.components[0];
var components_description = movement_select.components[0].description;
var components_premium = movement_select.components[0].premium;
var components_cover = movement_select.components[0].cover;
var components_commencementdate = movement_select.components[0].commencementdate;
// table 1 --------------------------------------------------
$("#id").html(id);
$("#refnr").html(refnr);
$("#movements_payer_fullname").html(movements_payer_fullname);
$("#movements_owner_fullname").html(movements_owner_fullname);
$("#refnr").html(refnr);
// table 2 --------------------------------------------------
}
and here is the JSON:
{
"policyid":"1000",
"refnr":"gcsa000923",
"movements":
[
{
"date":"2012/06/01",
"description":"Accept",
"premium":"R30.00",
"payer":{"personid":"928374","name":"Hansie","surname":"slim"},
"owner":{"personid":"928374","name":"Hansie","surname":"slim"},
"components":
[
{
"description":"Basic cover",
"premium":"R10.00",
"cover":"R0.00",
"commencementdate":"2012/06/01"
},
{
"description":"Cancer",
"premium":"R10.00",
"cover":"R20 000.00",
"commencementdate":"2012/06/01"
}
]
},
{
"date":"2012/08/01",
"description":"Policy Alteration",
"premium":"R30.00",
"payer":{"personid":"928374","name":"Hansie","surname":"slim"},
"owner":{"personid":"928374","name":"Hansie","surname":"slim"},
"components":
[
{
"description":"Basic cover",
"premium":"R10.00",
"cover":"R0.00",
"commencementdate":"2012/06/01"
},
{
"description":"Cancer",
"premium":"R10.00",
"cover":"R20 000.00",
"commencementdate":"2012/06/01"
},
{
"description":"Disability cover",
"premium":"R20.00",
"cover":"R40 000.00",
"commencementdate":"2012/09/01"
}
]
}
]
}
Solved:
for (c=0; c < components_count.length; c++)
{
$('#append').append("Description: " + components_count[c].description + " " + '<br>');
$('#append').append("Premium: " + components_count[c].premium + " " + '<br>');
$('#append').append("Cover: " + components_count[c].cover + " " + '<br>');
$('#append').append("Commencement Date: " + components_count[c].commencementdate + " " + '<br>' + '<br>');
}
I forgot about .append ^^

Categories

Resources