analyzing a string against an embedded structure

As someone who is just starting to learn code, I apologize if my question seems trivial.

I have a nested object database that I need to search for a character name and retrieve the corresponding owner of that character. Unfortunately, all the solutions I've come across so far only address searching at the top level or are specifically designed for arrays, leaving me feeling stuck and out of options. Is it possible to perform a deep search for a name like 'Farah' within the database and then somehow link it back to 'olis characters'?

Thank you in advance for any guidance or tips you may be able to provide!

{
  "olis characters": {
    "0": {
      "name": "Farah",
      "class": "rogue",
      "level": 74
    },
    "1": {
      "name": "Grop",
      "class": "paladin",
      "level": 31
    },
    "2": {
      "name": "Skolmr",
      "class": "druid",
      "level": 85,
    }
  },
  "chris characters": {
    "0": {
      "name": "Trygve",
      "class": "bard",
      "level": 28
    },
    "1": {
      "name": "Brusi",
      "class": "rogue",
      "level": 10
    },
    "2": {
      "name": "Steini",
      "class": "skald",
      "level": 58
    }
  }
}


Answer №1

It appears that your data structure is a bit unusual. The presence of numeric keys in an object suggests it should be an array instead. However, you can still extract the desired information by utilizing the Object.values method.

let data = {"olis characters": {"0": {"name": "Farah","class": "rogue","level": 74},"1": {"name": "Grop","class": "paladin","level": 31},"2": {"name": "Skolmr","class": "druid","level": 85,}},"chris characters": {"0": {"name": "Trygve","class": "bard","level": 28},"1": {"name": "Brusi","class": "rogue","level": 10},"2": {"name": "Steini","class": "skald","level": 58}}


function findChar(name, data) {
  for (let charGroup of Object.values(data)) {
    let found = Object.values(charGroup).find(char => char.name === name)
    if (found) return found
  }
}

console.log(findChar('Grop', data))
console.log(findChar('Brusi', data))

// will return undefined if the name is not there:
console.log(findChar('Mark', data))

If you were to modify the data structure to a simpler array format like this:

let data = {
    "olis characters": [{
        "name": "Farah",
        "class": "rogue",
        "level": 74
      },
      {
        "name": "Grop",
        "class": "paladin",
        "level": 31
      }
    ],
    "chris characters": [{
        "name": "Trygve",
        "class": "bard",
        "level": 28
      },
      // ...
    ]
 }

...you could eliminate one instance of using Object.values and directly apply the find method as shown below.

function findChar(name, data){
   for (let charGroup of Object.values(data)){
      let found = charGroup.find(char => char.name === name)
      if (found) return found
   }
 }

Answer №2

Running a loop through an object like this can be challenging, suggesting that using an array of objects instead of an object of objects may be more suitable.

Here is a code snippet that might assist you:

const data = {
    "olis characters": {
        "0": {
            "name": "Farah",
            "class": "rogue",
            "level": 74
        },
        "1": {
            "name": "Grop",
            "class": "paladin",
            "level": 31
        },
        "2": {
            "name": "Skolmr",
            "class": "druid",
            "level": 85,
        }
    },
    "chris characters": {
        "0": {
            "name": "Trygve",
            "class": "bard",
            "level": 28
        },
        "1": {
            "name": "Brusi",
            "class": "rogue",
            "level": 10
        },
        "2": {
            "name": "Steini",
            "class": "skald",
            "level": 58
        }
    }
}


Object.keys(data).forEach(key => {
    if(findItemByName('Farah', data[key])){
        console.log(key)
    }
})

function findItemByName(name, item) {
    let result = false;
    Object.keys(item).forEach(objKey => {
        if (item[objKey].name == name) {
            result = true;
        }

    });

    return result;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind the removal of the "disabled" attribute when setting the "disabled" property to false?

Initially, I have a disabled button: <button disabled="disabled">Lorem ipsum</button> When using button.getAttribute('disabled'), it returns "disabled". But once the button is enabled with JavaScript: button.disabled = false; The ...

Guide on aligning a popup next to the button that activated it using CSS and JavaScript

I am currently generating a dynamic quantity of divs, each containing a button that triggers a popup when clicked. I am attempting to position the popup below the specific button that activated it, but it remains static and does not move accordingly. <d ...

Error: GDAL is needed to initialize geometry from JSON input

Currently immersed in a Django project, I am eager to save polygons that can accurately represent specific areas of interest on a map. My approach involves utilizing django-leaflet and django-geojson. Here is an excerpt of the model I am employing to defin ...

The ng-repeat function is failing to show any data on the HTML view, instead only displaying a row for each property present

HTML Code: <div ng-repeat="addr in addrShipData"> <input type="radio" name="resp1" ng-checked='true'/> {{addr.addressLine1 +","+addr.addressLine2+", "+addr.city+ ","+addr.state+", "+addr.country+", "+addr.zipCode+","+addr ...

Encountering issues in transmitting form data to a Node server from Angular

In my Angular application, I am working on creating a registration page with validation. Once the user fills out the form and submits it, the data is sent to the server and saved in MongoDB. This is the approach I have taken: register_user() { const ...

Combining Struts2 JSON Plugin and Hibernate

I am in the process of trying to generate a JSON object from a List of AcaClasses. Here is an example of an Action Class: public class StudentJSONAction extends ActionSupport{ //The result List private List<AcaClass> gridModel; publi ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Tips for simultaneously dragging multiple items individually using JqueryUi sortable

I have conducted extensive research but have not found a suitable solution for my specific case. Below is the simplified version of my HTML structure: <div> <div> <ul class="sortable"> <li id="item-1"> ...

Tips for shutting down the camera within a modal by utilizing Html5 QrCode Scanner in ASP.NET MVC

Hey there! I'm currently working with the Html5 QrCode library to implement a scanner, and I've integrated it into a modal. However, I'm facing an issue where the camera continues running even after I close the modal. I'm wondering if t ...

An error occurred with the m.m.m.a.ExceptionHandlerExceptionResolver

I am getting an error in the backend console related to a value from React. How can I resolve this issue? [36m.m.m.a.ExceptionHandlerExceptionResolver Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [ ...

Should code in Vuejs be spread out among multiple components or consolidated into a single component?

After spending a significant amount of time working with Vue, I find myself facing a dilemma now that my app has grown in size. Organizing it efficiently has become a challenge. I grasp the concept of components and their usefulness in scenarios where the ...

I am struggling to understand how to properly utilize the data retrieved from the fetch api

I've been working with Javascript for less than a year and I always struggle with utilizing data from APIs. For example, when I fetch product information from an API, my console displays [{name:'pen',price:4},{name:'jeans',price:5 ...

Transforming DBF files into JSON format

Is there a C/C++ Library available for converting a Foxpro 2.6 Dos Data file (DBF - DBase III Format) into a JSON file, and vice versa? I am looking for a solution to convert DBF to JSON and back again. ...

Measuring data entries within JSON array utilizing JavaScript and Postman

A specific component is returning two records: { "value": [ { "ID": 5, "Pupil": 1900031265, "Offer": false, }, { "ID": 8, "Pupil": 1900035302, "Offer": false, "OfferDetail": "" } ] } My task i ...

What is the best way to thoroughly uninstall Ionic and Cordova from an Ubuntu system?

Is there a way to completely remove Cordova and Ionic 1 and all of their dependencies from my Ubuntu system? And how can I reinstall them again? I found this blog helpful for installing Ionic and its dependencies: I attempted to uninstall Cordova and Ion ...

Code for jQuery function

How do I update textareas with values after submitting a form? Below is the HTML code: <form id="productionForm" name="productionForm" method="POST"> <input type="text" id='ime_2'/> <textarea id='text_2'>& ...

Sort data with encryption based on chosen columns (table sort functionality)

I'm currently facing a challenge when it comes to sorting a table by column name. The data in the table is encrypted, so a simple sort by the column's direction (ascending or descending) isn't possible. I've been exploring options like ...

receiving a result from an asynchronous operation

Is there a way to retrieve the return value from this code snippet without using console log? function get_disk_space(callback){ checkDiskSpace('C:\\').then((diskSpace) => { var free = Math.floor(diskSpace.free/1000000000) ...

Parsing mimekit.MimeMessage Object

I'm encountering an issue when trying to deserialize a MimeKit.mimeMessage that I serialized into a JSON string and stored in a Redis key-value cache. Despite successfully serializing and storing the mimeMessage using either json.NET or Jil, I run in ...