Traverse a collection of nested objects containing arrays as their values

Consider the following object:

{
  "apples": [
    "one",
    "two"
  ],
  "oranges": [
    "three",
    "four"
  ]
}

If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below?

for (var i=0; i < obj.length; i++) {
  for (var y=0; y <obj.childObj.length; y++ {
    obj.childObj[i] === 'four' ? return : null;
  }
}

Alternatively, is there a more optimal way to organize and search through this data structure?

Answer №1

for(var key in object)
 if(object.hasOwnProperty(key)) {
  for(var nestedKey in object[key])
   if(object[key].hasOwnProperty(nestedKey)) {
    object[key][nestedKey] === 'four' ? performAction() : performAnotherAction();
   }
  }

MODIFY: Enhancement per recommendation from Matthew Herbst

Answer №2

To iterate through the elements in an object, you can utilize the for (x in y) statement:

var items = {
  "apples": [
    "red",
    "green"
  ],
  "oranges": [
    "orange",
    "tangerine"
  ]
};

for (var category in items) {
    var itemList = items[category];
    for (var i=0; i <itemList.length; i++) {
        // itemList[i] === 'green' ? return : null;
        console.log(itemList[i]);
    }
}

The output of this code snippet will be:

red
green
orange
tangerine

Answer №3

If you're on a quest to uncover whether this particular item contains the number four

var isFourPresent = Object.keys(obj).filter(function(val){ return obj[val].indexOf("four") != -1 }).length > 0;

To broaden its applicability

function findY(y)
{
   return Object.keys(obj).filter(function(val){ return obj[val].indexOf(y) != -1 }).length > 0;
}

Answer №4

Give this a shot ;)

Tweaked your script:

for (let x = 0; x < newArr.length; x++) {
  for (let y = 0; y < newArr[x].length; y++ {
    if(newArr[x][y] === 'four'){
      console.log("It's four");
    }
  }
}

Answer №5

To find a specific element in an object, you can utilize the indexOf method.


var fruits={
      "apples": [
        "one",
        "two"
      ],
      "oranges": [
        "three",
        "four"
      ]
    }
    for (var key in fruits) {
      if (fruits[key].indexOf("four") > -1)
        console.log("The element 'four' was found");
    }

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

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Tips for obtaining and storing multiple inputs within the same readline.question prompt in separate variables

Seeking to gather multiple user inputs in a single readline question and assign them to different variables? You're not alone! Ran into this challenge myself while trying to figure out the solution. Code import * as readline from 'node:readline&a ...

Python web application encountering issues running in browser

After successfully creating a Python desktop application with Tkinter library, we decided to convert it into a web app using pyjamas. The conversion process generated html files and javascripts as expected. However, when attempting to open the html file i ...

Reactjs: Could someone provide a more detailed explanation of this statement?

After reading this line in the documentation here, I came across an interesting code snippet. this.setState({ chats: [...this.state.chats, data], test: '' }); It seems like we are adding to the 'chats' array in the state, but I&ap ...

Trigger a click event to alter the child div elements

I have a <div> that expands when clicked and shrinks back when clicked again. Inside this div are images that should only appear once the div expands. My issue is ensuring that all images except the first one are hidden until the div expands. https: ...

Element mysteriously concealed in certain Safari cases, consistently visible in Firefox and Chrome

A new angular application has been developed as a "bounce" page for an upcoming social iOS app currently in public beta. Users have the ability to share their profiles by simply providing a link to the site. If the page is accessed via an iOS device w ...

The script fails to load when utilizing jquery/ajax

After the page loads, I am attempting to dynamically add a script into a div using ajax/jquery. This particular script is sourced from a CPM network and is responsible for loading a banner. However, when I try to load this script through ajax post-page lo ...

Navigating through a JMESPath query where a key may or may not be

My JSON data structure is a bit unusual (can't share actual data for security reasons, but here's the format). Here is the general structure: [ { "a": { "b": { "c": "d" } } ...

Replace all occurrences of a specific string throughout a extensive document in Node.js

I'm facing a challenge with handling large files in memory. I need to go through each line, replace any double quotes found, and update the file itself. Currently, I am reading the file line by line, storing it in an array, and then overwriting the sa ...

Adjusting the label on the Formik toggler

I have successfully implemented a switcher using Formik that changes the label accordingly with a boolean value. However, I now need to make the label reflect a string value instead of just "true/false." For example, I want it to display "Text1/Text2" inst ...

What is the reason for not receiving a JSON object in the response from my personal node.js/express server?

-- Exploring a New Challenge -- I am currently working on creating an e-form signup for a client as part of our business marketing strategy service. The form design is complete and looks excellent. Now, I need to connect it to the existing API that our bu ...

Putting together Modular Client-side JavaScript

Is there a way in Node.js to dynamically "require()" javascript files similar to PHP's require function? It would be great to use this feature in my client-side code for development purposes without actually calling a specific javascript function. Rat ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

Sending JSON data to a specific URL using cURL

I am searching on stackoverflow for a solution, but any help is appreciated. I need to send the following json-rpc code to another file which contains a bottle server: curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method":" ...

Preventing the default behavior using event.preventDefault() does not seem to be effective when submitting a

Why is the event.preventDefault() method not functioning properly? <script type="text/javascript" src="vue.js"></script> <div id="app"> <form v-on:submit.prevent="saveData"> <input type="text" name="test"> <button ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Tips for displaying "onclick" content beside dynamically generated content

I am working on a feature where a dynamically generated list has radio buttons displayed next to it. The goal is to show a dropdown list next to the specific radio button and list item that was changed. Essentially, if the radio button is set to "yes," I w ...

Utilize the 'response.download' method to retrieve unique data not typically expected for a given request

Each time I try to download a file, the response I get is different. The file is generated correctly every time: user,first_name,last_name,active,completed_training 4,Foo,Bas,YES,YES 5,Ble,Loco,NO,NO 9,gui2,md,NO,NO 3137,foo,baz,NO,NO However, the respons ...

Here is the code I have written to implement a date-picker event that retrieves specific records based on the selected date

I'm struggling with inserting a question here. Can someone provide assistance? $query = ("SELECT orders.customer_id, customer.name, customer.email, customer.address, customer.phone_number, orders.product_id, orders.total_units, orders.total_price, or ...

Looking to split the month and year input boxes when utilizing stripe version 7.2.0

Currently, I am utilizing ngx-stripe Version 7.2.0 to manage UI elements in Angular. I'm wondering if there is a method to split the Month and Year into separate text boxes within the UI of Angular 7 instead of having them combined into one field? ...