How do I get values from an array? - javascript

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.

Related

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))

Trace on nested objects couchdb update handler

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!

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 ^^

jQuery Nested Array..get immediate parent id

I have the following array
array = [
{
"id": "67",
"sub": [
{
"id": "663",
},
{
"id": "435",
}
]
},
{
"id": "546",
"sub": [
{
"id": "23",
"sub": [
{
"id": "4",
}
]
},
{
"id": "71"
}
]
}
]
I am currently looping throught the array as follows
calling the array:
processArray(array);
the function loop
function processArray(arr)
{
for(var item in arr) {
var value = arr[item];
var order = item;
var itemID = value.id;
if(itemID != null)
{
$('.text').append(" ORDER : " + order + " Item ID : " + itemID + "<br />" );
}
if(typeof(value) == 'object') { //If it is an array,
processArray(arr[item]);
}
}
}
Currently i am getting the order of the item and the current ID no problem. What i need however (for my database schema) is for each item get the ID of its parent if there is one.
Do i need to pass the parent to each node? Or is there an easier way?
Thanks
Working demo
Include an optional parameter parentID in the function; by doing this, you can still use the processArray(array); syntax to process the original array.
function processArray(arr, parentID)
{
for(var item in arr) {
var value = arr[item];
var order = item;
var itemID = value.id;
if(itemID != null)
{
var output = " ORDER : " + order + " Item ID : " + itemID;
if( parentID ) { output += " PARENT : " + parentID; }
$('.text').append( output + "<br />");
}
// PROCESS SUB-ARRAY
if( typeof(value.sub) == 'object') { //If it is an array,
processArray( value.sub, itemID );
}
}
}
Use an auxiliary function that has id as part of its signature:
function processArray(arr) {
function _processArray(arr, id) {
for (var item in arr) {
var value = arr[item];
var order = item;
var itemID = value.id; // you need to change this because on the second call you pass in a string and not just an object
var parentId = id;
// Commenting the if statement that you had here actually shows the parent id's now.
$('.text').append(" ORDER : " + order + " Item ID : " + itemID + " Parent Id : " + parentId + "<br />");
if (typeof value === "object") { //use instanceof,
_processArray(arr[item], itemID);
}
}
}
_processArray(arr, 0);
}

Categories

Resources