logo
down
shadow

find recursively a JSON value


find recursively a JSON value

By : JRV
Date : November 22 2020, 09:00 AM
To fix the issue you can do These are just Javascript Objects. You are looking to do a deep search. Here's a way you could do it:
code :
function deepKeySearch(obj, key) {
  for (iKey in obj) {
    if (obj.hasOwnProperty(iKey)) {
      if (iKey === key) {
        return obj[iKey];
      } else if (typeof obj[iKey] === 'object' && obj[iKey] !== null) {
        var search = deepKeySearch(obj[iKey], key);
        if (search !== undefined) {
          return search;
        }
      }
    }
  }
}

var obj = {
  obj: {
    obj: {
      menu: 'Hey',
      arrTest: [0]
    }
  }
}

console.log(deepKeySearch(obj, 'menu') !== undefined); //does exist
console.log(deepKeySearch(obj, 'nonExistantKey') !== undefined); //doesn't exist
console.log(deepKeySearch(obj, 'arrTest') !== undefined); //does exist
function deepKeySearch(obj, key) {
    var keys = Object.keys(obj);
    return keys.some(function (iKey) {
        if (iKey === key) {
            return true;
        } else if (typeof obj[iKey] === 'object' && obj[iKey] !== null) {
            return deepKeySearch(obj[iKey], key);
        }
    });
}

var obj = {
    obj: {
        obj: {
            menu: 'Hey',
            arrTest: [0]
        }
    }
}

console.log(deepKeySearch(obj, 'menu')); //does exist
console.log(deepKeySearch(obj, 'nonExistantKey')); //doesn't exist
console.log(deepKeySearch(obj, '0')); //does exist


Share : facebook icon twitter icon
Javascript find recursively in JSON object

Javascript find recursively in JSON object


By : tushar dixit
Date : March 29 2020, 07:55 AM
this one helps. You could do something like the below, which looks for keys that match needle
code :
var foobar = {
    "foo": {
        "whooop" : {
        "bar" : 123
        }
    }
};

function isInArray(needle, haystack) { 
    var foundNeedle = false;

    for (var key in haystack) {

        if (isInArray(needle, haystack[key])) {
            foundNeedle = true;
        }

        if (key == needle) {
            foundNeedle = true
        }
    }

    return foundNeedle;    
}  

var message = "is bar in foobar? result is... " +  isInArray("bar", foobar));
Find recursively a JSON value and return object

Find recursively a JSON value and return object


By : user2610127
Date : March 29 2020, 07:55 AM
it should still fix some issue I think to problem occurs when you type the caracters in different case, you can transform the search term to lowercase to resolve that issue.
code :
var object = {
    "categories": [
        {
            "id": 1,
            "name": "Brands and Organizations",
            "type": "dir",
            "children": [
                {
                    "id": 2,
                    "name":"Apple",
                    "parentId": 1,
                    "children": [
                        {
                            "id": 8,
                            "name":"Iphone",
                            "parentId": 2
                        }
                    ]
                },
                 {
                    "id":3,
                    "name":"Samsung",
                    "parentId": 1
                }
            ]
        },
        {
            "id": 4,
            "name": "Media",
            "type": "dir",
            "children": [
                {
                    "id": 5,
                    "name":"CD",
                    "parentId": 4
                },
                 {
                    "id":6,
                    "name":"DVD",
                    "parentId": 4
                }
            ]
        },
        {
            "id": 7,
            "name": "Inlfuenser",
            "type": "dir",
            "children": null
        }
    ]
};


function filterJson(categories, search) {

   var search = search.toLowerCase().trim();
   var matches = [];
    if (!Array.isArray(categories)) return matches;

    categories.forEach(function(category) {

        if (category.name.toLowerCase().includes(search)) {
            matches.push(category);
        } else {
            let childResults = filterJson(category.children, search);
            if (childResults.length)
                matches.push(Object.assign({}, category, { children: childResults }));
        }
    })

return matches;
}

function filter(value) {
console.log(value);
var matches = filterJson(object.categories, value);
console.log(matches);
document.getElementById('matches').innerHTML = JSON.stringify(matches);
}
<input type="text" onchange="filter(this.value)" />

<div id="matches"></div>
Find first json object with given key name recursively using jq

Find first json object with given key name recursively using jq


By : user2869028
Date : March 29 2020, 07:55 AM
this will help How can I find recursively first key with given name using jq? , To select just the first, use first:
code :
first(.. | objects | select(has("model")))
first(..|select(.model?))
jq -n 'first(inputs|..|select(.model?))'
Find dependency from json recursively

Find dependency from json recursively


By : user3660880
Date : March 29 2020, 07:55 AM
hope this fix your issue You could convert the data to a hash table and get the dependencies by using a recursion.
It is still quite unclear, what you want with the leaves.
code :
function getDependencies(data, StoryID) {
    function getProperty(k) {
        return function (o) { return o[k]; };
    }

    function getD(r, StoryID) {
        r[StoryID] = object[StoryID].reduce(getD, {});
        return r;
    }

    var object = data.reduce(function (r, o) {
            r[o.StoryID] = (o.Dependencies || []).map(getProperty('StoryID'));
            return r;
        }, {});

    return [StoryID].reduce(getD, {});
}

var data = [{ StoryID: "B-1", Dependencies: [{ StoryID: "B-2" }, { StoryID: "B-3" }] }, { StoryID: "B-2", Dependencies: [] }, { StoryID: "B-3", Dependencies: [{ StoryID: "B-4" }, { StoryID: "B-5" }] }, { StoryID: "B-4", Dependencies: [] }, { StoryID: "B-5", Dependencies: [{ StoryID: "B-6" }] }, { StoryID: "B-6", Dependencies: [] }],
    result =  getDependencies(data, 'B-3')

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
recursively find parents in JSON array backward connect by prev value

recursively find parents in JSON array backward connect by prev value


By : user3714999
Date : March 29 2020, 07:55 AM
To fix the issue you can do If you want to avoid a search through the whole tree whenever you need this, it is better to first preprocess your tree, so that you can find any node (object) directly, in constant time, given its secCode.
You can create a Map for that connection between secCode and node:
code :
// Creates a map which is keyed by secCode, and for a secCode provides 
//   the corresponding node from the tree
function createMap(tree) {
    let map = new Map;
    
    function recur(node) {
        map.set(node.secCode, node);
        if (node.children) node.children.forEach(recur);
    }
    
    tree.forEach(recur);
    return map;
}

// Uses the map to walk up the tree
function getParents(secCode, map) {
    let parents = [];
    while (secCode) {
        parents.push(secCode);
        let node = map.get(secCode);
        secCode = node.prevSec;
    }
    return parents;
}

// The tree from the question:
let tree = [{"secCode": 2,"secName": "GENERAL NURSING CARE SECTION","prevSec": 0,},{"secCode": 1,"secName": "CRITICAL CARE NURSING SECTION","prevSec": 0,"children": [{"secCode": 3,"secName": "OPERATION THEATRE","prevSec": 1,"children": [{"secCode": 5,"secName": "MAIN OPERATION THEATRE","prevSec": 3,"estCode": 152,},{"secCode": 6,"secName": "DAY CARE DT SERVICE","prevSec": 3,}]},{"secCode": 4,"secName": "CRITICAL CARE SERVICES","prevSec": 1,"children": [{"secCode": 675,"secName": "Test","prevSec": 4,"children": [{"secCode": 676,"secName": "Test1","prevSec": 675,},{"secCode": 677,"secName": "Test 2","prevSec": 675,},{"secCode": 678,"secName": "Test 3","prevSec": 675,},{"secCode": 679,"secName": "Test 4","prevSec": 675,}]},{"secCode": 7,"secName": "ACUTE CARE","prevSec": 4,}]}]}];
// Preprocessing
let map = createMap(tree);
// Example calls:
console.log(getParents(7, map));
console.log(getParents(679, map));
class Tree {
    constructor(data) {
        this.map = new Map;

        const recur = (node) => {
            this.map.set(node.secCode, node);
            if (node.children) node.children.forEach(recur);
        }

        data.forEach(recur);
    }
    getParents(secCode) {
        let parents = [];
        while (secCode) {
            parents.push(secCode);
            secCode = this.map.get(secCode).prevSec;
        }
        return parents;
    }
}

// The tree from the question:
let data = [{"secCode": 2,"secName": "GENERAL NURSING CARE SECTION","prevSec": 0,},{"secCode": 1,"secName": "CRITICAL CARE NURSING SECTION","prevSec": 0,"children": [{"secCode": 3,"secName": "OPERATION THEATRE","prevSec": 1,"children": [{"secCode": 5,"secName": "MAIN OPERATION THEATRE","prevSec": 3,"estCode": 152,},{"secCode": 6,"secName": "DAY CARE DT SERVICE","prevSec": 3,}]},{"secCode": 4,"secName": "CRITICAL CARE SERVICES","prevSec": 1,"children": [{"secCode": 675,"secName": "Test","prevSec": 4,"children": [{"secCode": 676,"secName": "Test1","prevSec": 675,},{"secCode": 677,"secName": "Test 2","prevSec": 675,},{"secCode": 678,"secName": "Test 3","prevSec": 675,},{"secCode": 679,"secName": "Test 4","prevSec": 675,}]},{"secCode": 7,"secName": "ACUTE CARE","prevSec": 4,}]}]}];
// Preprocessing
let tree = new Tree(data);
// Example calls:
console.log(tree.getParents(7));
console.log(tree.getParents(679));
Related Posts Related Posts :
  • gulp-minify without rename original files
  • create a link to run javascript in another window
  • Javascript, Uncaught TypeError: Cannot read property "cells" of undefined
  • Express.js and Sequelize: does not define models
  • Serialize table data as IEnumerable within asp.net WebApi
  • Handle WebPack CSS imports when testing with Mocha and Babel
  • Converting JSON string to Angular function?
  • Bootstrap-multiselect is very slow with a large pool of options
  • Writing back to HTML after reading form input doesn't work (Javascript)?
  • Kendo UI Grid: Get the data of Current Grouping state?
  • A function to test if all svg objects are visible
  • how to change src without reloading the page
  • side menu with drop down menu
  • How to store timestamp a JSON object?
  • HTML5 Form Submit
  • Caret Sensurround by circle CSS
  • Chrome local storage deleting after NWJS application closes on Windows
  • cordova inappbrowser referencing elements
  • Passing multiple variables to another page
  • $.when with arbitrary number of deferred objects?
  • Printing different part of page depending on clicked element
  • Read in cookie to Shiny application with embedded javascript
  • Asynchronous array problems
  • Disable button if certain number of checkbox are checked
  • Write a loop that finds a value and returns a color
  • How to make the page layout stay the same after minimized?
  • Looping div elements using jquery
  • Node.js 'request' module wrapper with optional params - how to write this more concise?
  • Javascript , Object property is shown as undefined
  • How to trigger and wait for the result of a notification from a call back function of an event listener
  • How to populate a form box with javascript based on other form box inputs
  • Default/Overridable content for Aurelia template (template parts)
  • Ember, how to reuse same "partial" for "index" and for "show"
  • Display content from database on HTML page via Ajax and PHP
  • exporting logic as a function in express.js
  • Verifying Docusign Connect Signature with X509 Certificate
  • React js get the value from div
  • What does the notation () => mean and how to use it?
  • JQuery Hide/Show one, not all
  • Split string on backslash or forward slash
  • PHP Inside JavaScript - Quotes Issue?
  • ReactJS Unexpected Token ) on Safari only
  • Use lodash to group array into tree "children" structure
  • With D3, how can I avoid SVG graph links being rendered over nodes?
  • Consolidate nested, overlapping <strong> and <em> tags
  • How to Access an array of objects properties?
  • Simple Push Menu in CSS3 and jQuery
  • addEventListener not working for onDragStart
  • Partial string matching in javascript
  • Posting a title along with a Photo using the FB.api
  • Why is my jquery code not working or throwing any errors?
  • Javascript/jquery - Wrap text with tag at specific position
  • Javascript Canvas can't draw multiple curves
  • Javascript move entire span with arrow keys
  • How to stop my character from going outside the div?
  • How to call in plugin options in jquery plugins
  • Remove default submit on modal form button
  • Generate angular model properties by view, when view fields are empty
  • AngularJS - project files layout, injection and scope clarification
  • get text fields that are not empty
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co