jQuery Nested Array..get immediate parent id - javascript

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

Related

RegEx repeating capture

Can a RegEx be created to pull the same pattern over and over?
https://regex101.com/r/BEOHLh/2/
Tried something like this too:
.* [(.*?)='(.*?)']{0-5}.*
to allow for everything in square brackets to repeat.
I could parse it without RegEx, but seem like RegEx would be the best. I'm converting some WordPress shortcodes to a NodeJS based system. Need to extract id and label (either one may be optional), so here are three test cases and the code I tried.
var testArray = ["[include_word id='110']", "[include_word label='bah']", "[include_word id='987' label='bah-beh']"];
testArray.forEach (processArrayItemRegex);
function processArrayItemRegex (item, index) {
console.log ("index:" + index + " item:" + item);
//var regexPattern = /.*id='(<id>.*?)'.*label='(<label>.*?)'.*/g;
//var regexPattern = /.*(?:id='(.*?)').*(?:label='(.*?)').*/g;
var regexPattern = /.* (.*?)='(.*?)'.*/g;
//const { groups: segments } = item.match(regexPattern);
var segments = item.match(regexPattern);
console.dir(segments, { depth: null });
//console.log(segments);
id = segments[0];
label = segments[1];
console.log("id=" + id + " label=" + label);
}
Current output:
index:0 item:[include_word id='110']
[ '[include_word id=\'110\']' ]
id=[include_word id='110'] label=undefined
index:1 item:[include_word label='bah']
[ '[include_word label=\'bah\']' ]
id=[include_word label='bah'] label=undefined
index:2 item:[include_word id='987' label='abc']
[ '[include_word id=\'987\' label=\'abc\']' ]
id=[include_word id='987' label='abc'] label=undefined
The code below works to convert it to JSON and let's me access the variables, it's just not as elegant as I would like:
function processArrayItem (item, index) {
console.log ("index:" + index + " item:" + item);
//remove unneeded wrappers
item = item.replace("include_word ","")
item = item.replace("[","{").replace("]","}");;
item = item.replace(/'/g, '"');
item = item.replace('id=','"id":');
item = item.replace('label=','"label":');
item = item.replace('transliteration=','"transliteration"');
var itemObj = JSON.parse(item);
console.log("id=" + itemObj.id + " label=" + itemObj.label);
}
If I understand correctly, the thing you're missing is the matchAll function.
Try this as a starting point:
for (let match of "[include_word id='987' label='bah-beh']".matchAll(
/(\S+)='(\S+)'/g
)) {
console.log({ key: match[1], value: match[2] });
}
I am not sure whether this is what you want,
testArray.forEach (processArrayItemRegex);
function processArrayItemRegex (item, index) {
console.log ("index:" + index + " item:" + item);
var regexPattern = /(\S+)='(\S+)'/g;
//console.log(regexPattern);
var id = label = 'undefined';
var segments ;
while ((segments = regexPattern.exec(item)) != null)
{
//console.dir(segments , { depth: null });
var key = segments [1];
var value = segments [2];
if (key == 'id')
id = value;
if (key == 'label')
label = value;
};
console.log("id=" + id + " label=" + label);
}
Console output:
index:0 item:[include_word id='110']
id=110 label=undefined
index:1 item:[include_word label='bah']
id=undefined label=bah
index:2 item:[include_word id='987' label='bah-beh']
id=987 label=bah-beh

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!

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 finding integer attribute value inside object array

This is basically something that makes zero logical sense, and I'm not sure why this is happening.
When you create a function to compare attribute values of an array of objects (essentially JSON object), it refuses to find the index. However, OUTSIDE the function, it seems to work perfectly fine.
However, the problem is
var peoples = [
{ "name": 44, "dinner": "pizza" },
{ "name": 65, "dinner": "sushi" },
{ "name": 33, "dinner": "hummus" }
];
var val = 33;
$("#t").append(get_index_of_array_based_on_value(peoples, val));
function get_index_of_array_based_on_value(array, val) {
$.each(array, function (index, obj) {
$.each(obj, function (attr, value) {
console.log(" attr: " + attr + " == " + value + " (" + val + ") {{" + index + "}} ");
if (value == val) {
return index;
}
});
});
}
http://jsfiddle.net/QStkd/2327/
The above does not work.
The below script does work.
http://jsfiddle.net/QStkd/2330/
The below script is simply the same script except outside the function. When you put stuff into functions it suddenly refuses to find the index based on the value.
You cannot return a value from a $.each call. You are inside a callback, your return doesn't affect the main function.
When you use return inside the $.each callback, it's similar to break/continue in a for/while loop. A falsy value will break the loop, and a truthy value is like calling continue.
You need to return from the main function, get_index_of_array_based_on_value, not from the $.each.
function get_index_of_array_based_on_value(array, val) {
var returnVal = null;
$.each(array, function (index, obj) {
$.each(obj, function (attr, value) {
console.log(" attr: " + attr + " == " + value + " (" + val + ") {{" + index + "}} ");
if (value == val) {
returnVal = index;
return false; // break;
}
});
if(returnVal !== null){
return false; // break the outer loop
}
});
return returnVal;
}
thy this
var peoples = [
{ "name": 44, "dinner": "pizza" },
{ "name": 65, "dinner": "sushi" },
{ "name": 33, "dinner": "hummus" }
];
var val = 33;
$("#t").append(get_index_of_array_based_on_value(peoples, val));
function get_index_of_array_based_on_value(array, val) {
for(var index = 0; index < array.length; index++){
for(var attr in array[index]) {
var value = array[index][attr];
console.log(" attr: " + attr + " == " + value + " (" + val + ") {{" + index + "}} ");
if (value == val) {
return index;
}
}
}
}

Too much recursion error on firefox jquery

I'm getting too much recursion error at the following piece of code, when I'm running the application on Firefox. The code is expected to create a graphical tree structure in the browser. The method take a Json as an input, traverses through the keys and checks if the value corresponding to the key is "Leaf". If the value is "Leaf", it displays it on the browser and moves on to the next key, else it traverses recursively through the child nodes till the "Leaf" is reached. The node with all its children are displayed on the browser:
function createmasterJson(data) {
var json = '';
for (var index in data) {
var child = data[index];
if (child == 'Leaf') {
json = json + createLeafNode(index);
} else {
if (child.length) {
for (var i = 0; i < child.length; i++) {
json = json + createNonLeafNode(index, createmasterJson(child[i]));
}
} else {
json = json + createLeafNode(index);
}
}
}
return json;
}
function createLeafNode(index){
return '{ "attributes": { "id" :"' + index + '_' + Math.random() +'"}, "data": " '+ index +'" },';
}
function createNonLeafNode(index, child){
return '{ "attributes": { "id" :"' + index + '_' + Math.random() +'"}, "data": " '+ index +'" ,"state": "closed", "children" : ['+child.substring(0, child.length - 1)+']},';
}

Categories

Resources