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

Why is my PanResponder failing to detect changes in the updated state?

This is the code snippet I'm currently working on: const processPinch = (x1: number, y1: number, x2: number, y2: number) => { function calcDistance(x1: number, y1: number, x2: number, y2: number) { const dx = x1 - x2; const dy = y1 ...

What's the best way to display a bootstrap modal window popup without redirecting to a new page?

I am having trouble implementing a modal window that will display validation errors to the user when they submit a form. Currently, the window is opening as a new view instead of overlapping the existing form's view. How can I adjust my code so that t ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

Efficient communication in Angular: Sharing data among controllers and components

Recently joining a new project, I am faced with the task of implementing a small feature. In my setup, there are 2 distinct views: Cars.html and Wheels.html The Cars.html view is associated with the controller Cars.controller.js On the other hand, the W ...

AngularJS does not support the use of $(this) syntax

I have encountered an issue while developing a Chrome extension using AngularJS. I would like to add buttons to my popup page, and I want the ancestor node to disappear when a button is clicked. Here is the code snippet: in popup.html <div class="dea ...

Converting JSON data to a DirectionsRoute object: A simple guide

I am currently working on developing a basic navigator for Android using the mapbox API. I have been creating some routes through the https://docs.mapbox.com/playground/directions/ playground and my aim is to utilize the JSON data generated from it in orde ...

Is there a way to transfer JavaScript data to PHP?

<div> <p>This is a sample HTML code with JavaScript for tallying radio button values and passing them to PHP via email.</p> </div> If you need help converting JavaScript data to PHP and sending it via email, there are v ...

Issues arise with transferring React component between different projects

My goal is to develop a React component that serves as a navigation bar. This particular component is intended to be imported from a separate file into my App.js. Currently, the component is designed to simply display a 'Hello world' paragraph, ...

The timestamp will display a different date and time on the local system if it is generated using Go on AWS

My angular application is connected to a REST API built with golang. I have implemented a todo list feature where users can create todos for weekly or monthly tasks. When creating a todo, I use JavaScript to generate the first timestamp and submit it to th ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

I encountered an issue with rendering static images when attempting to package my node-express app with pkg

Struggling to display an image from the public folder in my express app? I could use some guidance on configuring the path to properly render images or css files within the public folder when creating an executable file using pkg. Here's a snippet of ...

performing nested queries in nodejs using a callback function

Over the course of my research, I've come across numerous examples of one-to-many relations. However, I have yet to find a clear-cut example demonstrating how to solve nested queries for normalized data in 'mongodb'. Perhaps it's just m ...

Identifying when a fetch operation has completed in vue.js can be accomplished by utilizing promises

Currently, I am facing a dilemma in my Vue.js application. I am making an API call within the created() hook, but there are certain tasks that I need to trigger only after the API call has been completed. The issue is that this API call usually takes aroun ...

What is the process for loading this image?

While browsing through this stunning website, I came across a feature that caught my eye. Can someone please explain how the designer displayed the "The magic is loading" effect: The image vanishes once the site has finished loading completely. ...

Is there a way to customize the selected option in the autocomplete feature of Material UI components?

Is it possible to customize the CSS of selected options in Material UI autocomplete? Can this be achieved by utilizing the theme? ...

Unable to update a single object within an array using the spread operator

I am currently working on updating an object within an array and have encountered some issues. In my initial code, I successfully updated a specific property of the object inside the array like this: var equipment = this.equipments.find((e) => e.id === ...

Guide to developing a custom plugin for Nuxt.js

This is the content of my rpc.js plugin file: const { createBitcoinRpc } = require('@carnesen/bitcoin-rpc') const protocol = 'http' const rpcuser = 'root' const rpcpassword = 'toor' const host = '127.0.0.1&apo ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...

What is the best way to transfer variables to a different page through a pop-up window?

I'm working with a function that converts the Id of the clicked element into a variable, then opens a new window with a different page. How can I access or utilize this variable on the newly opened page? var idToWrite = []; $(function(){ $(".szl ...