Locate a specific item within an array that is nested within another array

let bigArray = [
{
    Name: 'Trump',
    children: [
                 {Name: 'TrumpChild1', City: 'city1'}, 
                 {Name: 'TrumpChild2', City: 'city2'}
    ]
},
{
    Name: 'Barack Obama',
    children: [
                 {Name: 'Barack Obama Child1', City: 'city3'}, 
                 {Name: 'Barack Obama Child2', City: 'city4'}
    ]
},
{
    Name: 'Clinton',
    children: [
                 {Name: 'Clinton Child 1', City: 'city5'}, 
                 {Name: 'Clinton Child2', City: 'city6'}
    ]
},

]

Is there a better way to search for an object nested inside another array within the bigArray?

bigArray.find(b => b.children.find(c=>c.City === 'city1'))

The code above returns the ARRAY father, is there a more efficient approach?

bigArray.forEach(b => b.children.find(c=>c.City === 'city1'))

This line of code just returns undefined. What would be the best method to retrieve the desired object?

Answer №1

To start, flatten the array into inner objects and then employ the filter() method or the find() method.

let bigArray = [
  {
      Name: 'Trump',
      children: [
                   {Name: 'TrumpChild1', City: 'city1'}, 
                   {Name: 'TrumpChild2', City: 'city2'}
      ]
  },
  {
      Name: 'Barack Obama',
      children: [
                   {Name: 'Barack Obama Child1', City: 'city3'}, 
                   {Name: 'Barack Obama Child2', City: 'city4'}
      ]
  },
  {
      Name: 'Clinton',
      children: [
                   {Name: 'Clinton Child 1', City: 'city5'}, 
                   {Name: 'Clinton Child2', City: 'city6'}
      ]
  }
];

let all = bigArray.reduce((prev, next) => prev.concat(next.children), []);
let result = all.find(obj => obj.City === 'city1');
console.log(result);

// if there can be multiple matches then use filter
let results = all.filter(obj => obj.City === 'city1');
console.log(results);

Answer №2

In scenarios where children are born in the same city, using find() may not be the best approach as it only retrieves the first result it finds. Instead, we can utilize filter().

This solution incorporates calling filter within reduce(). This method differs from other solutions by minimizing iterations through the input data. The alternative approach presented here processes each president once and adds any matching children along the way.

const findByCity = (city, data = {}) =>
  data .reduce
    ( (result, { children = [] }) =>
        result .concat (children .filter (c => c.city === city))
    , []
    )

Considering that each child in the input data has a unique city, this example may not provide a clear demonstration. To showcase results with multiple children sharing the same birth city of city5, additional entries have been included.

const data =
  [ { name: 'Trump'
    , children:
        [ { name: 'Trump Child 1', city: 'city1' }
        , { name: 'Trump Child 2', city: 'city2' }
        ]
    }
  , { name: 'Barack Obama'
    , children:
        [ { name: 'Barack Obama Child 1', city: 'city3' }
        , { name: 'Barack Obama Child 2', city: 'city4' }
        ]
    }
  , { name: 'Clinton'
    , children:
        [ { name: 'Clinton Child 1', city: 'city5' }
        , { name: 'Clinton Child 2', city: 'city6' }
        ]
    }
  , { name: 'Bush'
    , children:
        [ { name: 'Bush Child 1', city: 'city5' }
        , { name: 'Bush Child 2', city: 'city5' }
        ]
    }
  ]

console .log (findByCity ('city1', data))
// [ { name: 'Trump Child 1', city: 'city1' } ]

console .log (findByCity ('city5', data))
// [ { name: 'Clinton Child 1', city: 'city5' }
// , { name: 'Bush Child 1', city: 'city5' }
// , { name: 'Bush Child 2', city: 'city5' }
// ]

An important distinction is how another solution might fail if data includes a president without any children listed. In contrast, the findByCity function avoids encountering such issues.

const data =
  [ // ...
  , { name: 'Bush'
    , children:
        [ { name: 'Bush Child 1', city: 'city5' }
        , { name: 'Bush Child 2', city: 'city5' }
        ]
    }

  // Caution required for presidents with no children!
  , { name: 'Polk' }
  ]

Feel free to expand on the provided program code and run it within your browser environment.

const findByCity = (city, data = {}) =>
  data .reduce
    ( (result, { children = [] }) =>
        result .concat (children .filter (c => c.city === city))
    , []
    )

const data =
  [ { name: 'Trump'
    , children:
        [ { name: 'Trump Child 1', city: 'city1' }
        , { name: 'Trump Child 2', city: 'city2' }
        ]
    }
  , { name: 'Barack Obama'
    , children:
        [ { name: 'Barack Obama Child 1', city: 'city3' }
        , { name: 'Barack Obama Child 2', city: 'city4' }
        ]
    }
  , { name: 'Clinton'
    , children:
        [ { name: 'Clinton Child 1', city: 'city5' }
        , { name: 'Clinton Child 2', city: 'city6' }
        ]
    }
  , { name: 'Bush'
    , children:
        [ { name: 'Bush Child 1', city: 'city5' }
        , { name: 'Bush Child 2', city: 'city5' }
        ]
    }
  , { name: 'Polk' }
  ]


console .log (findByCity ('city1', data))
// [ { name: 'Trump Child 1', city: 'city1' }]
    
console .log (findByCity ('city5', data))
// [ { name: 'Clinton Child 1', city: 'city5' }
// , { name: 'Bush Child 1', city: 'city5' }
// , { name: 'Bush Child 2', city: 'city5' }
// ]

Answer №3

Another way to achieve this is by not flattening the array.

let results = [];

// Using array.forEach(), along with the && operator in .map() for concise comparison
bigArray.forEach(obj => {obj.children.map(c => c.City == 'city1' &&  results.push(c))});

// This approach also functions even if there isn't a `children` property in the objects
bigArray.forEach(obj => {obj.children && obj.children.map(c => c.City == 'city1' &&  results.push(c))});

Answer №4

I faced a similar issue recently, but in my case, I needed to retrieve the overall name of the element, specifically the father's name (e.g., 'Trump'). To achieve this efficiently, I utilized a double find approach. Here is an excerpt from my code:

let bigArray = [
  {
      Name: 'Trump',
      children: [
                   {Name: 'TrumpChild1', City: 'city1'}, 
                   {Name: 'TrumpChild2', City: 'city2'}
      ]
  },
  {
      Name: 'Barack Obama',
      children: [
                   {Name: 'Barack Obama Child1', City: 'city3'}, 
                   {Name: 'Barack Obama Child2', City: 'city4'}
      ]
  },
  {
      Name: 'Clinton',
      children: [
                   {Name: 'Clinton Child 1', City: 'city5'}, 
                   {Name: 'Clinton Child2', City: 'city6'}
      ]
  }
];

const element = bigArray.find((el) => el.children.find((item) => item.City === 'city2'))
const {Name: fatherName} = element
// retrieve the element
console.log(element)
// retrieve the father's name 
console.log(fatherName)

If you only require the name, you can replace `element` with `{Name: fatherName}`.

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

Manipulating arrays within Vuejs does not trigger a re-render of table rows

I have successfully generated a user table using data retrieved from an ajax request. The table has a structure similar to this: [Image of Table][1] Now, when an admin makes changes to a user's username, I want the respective row to update with the n ...

Obtaining a dependency directly from the Injector within a directive

I am currently working on developing a versatile directive that can take a class type for validating rules. Depending on the rule specified in the class, the directive will either display or hide an element. This is my progress so far. Check out the PLUN ...

The react router fails to navigate nested paths within S3 directories

In my setup with react-router-dom, it looks like this: <Router> <Routes> <Route path="/" element={<Home />} /> <Route path="/post/:slug" element={<Post />} /> // other rout ...

Leveraging functions and callback within Node.js

Struggling with node.js and function calls here. The issue is that when I call a function, node.js doesn't wait for it to complete, resulting in empty return values. Below is the code snippet: exports.handle = (event, context,callback) => { switch ...

What is the best way to ensure messages are sequentially delivered in NodeJS?

I've successfully deployed a node server responsible for updating the database with the connectivity status of IOT devices. Issue Due to the asynchronous nature of NodeJS and its single-threaded execution, there is a possibility of receiving confli ...

Guide to developing and showcasing a proof of concept (PoC) for a Google Chrome vulnerability using Out of Bounds (oob) method

While reading through an article discussing the Proof of Concept of a CVE in Google Chrome (OOB issue), I came across this intriguing code snippet: (https://medium.com/@elniak/cve-2024-4761-exploiting-chromes-javascript-engine-highly-exploited-poc-presente ...

Determine the gravitational force of a planet on falling objects and display the result in an input field

I have developed a form code that includes several dropdown menus with different options, as well as an alert popup message to prevent users from selecting the same planet more than once. Additionally, I have disabled one input in a textbox because only on ...

What is the best way to add elements to a blank 2D array in Javascript?

As I delve into the contents of a text file, I encounter rows separated by the string OUT_ and columns delimited by \n My task involves filtering out arrays with less than 9 columns and without a % in the 6th column Once filtered, the goal is to alp ...

The instance does not have a definition for the property or method "foo" that was referenced during rendering

[Vue warn]: Property or method "modelInfo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. Whenever I ...

The functionality for accessing objects in Chrome Developer Tools is not functioning properly

Every time I attempt to access an object in Chrome Developer Tools, I encounter the following error message: VM4939:1 Uncaught TypeError: Cannot read property 'cells' of undefined at :1:13 Here is my code: <head> <script> ...

An element in CSS that has a position of fixed and a width of 100% surpasses the dimensions of its

My element has the CSS properties position:fixed and width:100%, causing it to be larger than its parent elements. Despite the complexity of my code, I have attempted to simplify it for better understanding. Below, you can see that the green box exceeds ...

Having an issue with the Next Button functionality in my Swift quiz application

ScreenshotThis quiz app has been a popular choice among users, so I decided to create my own version of it. I stored the question array QlistsA in a separate file, but I'm facing challenges when it comes to communicating with it effectively. Although ...

Transmit Array of Preferred Values to Controller in MVC Framework

After setting up a view with a search box and buttons labeled "Add" (btn-default) and "Edit" (breadcrumb), I encountered an issue when attempting to pass selected values from the search box to another controller upon clicking the Edit button. Unfortunately ...

Reference to the register value within array C

I'm currently utilizing an STM32F303RE microcontroller. Here is the array I am working with: int regvals[] = { GPIOA->MODER, GPIOA->OTYPER, GPIOA->OSPEEDR, GPIOA->PUPDR, GPIOA->IDR, GPIOA->ODR, GPIOA->BSRR, GPIOA->LCKR, GPIOA-& ...

Modify website styling using JavaScript to edit external CSS/SCSS files

I am looking to 'modify' a file that is stored on my server, for example: <link rel="stylesheet" href="css/plugin.scss"> Not only that, but I also want to specifically edit a line within the SASS file. In SASS, you can declare variables i ...

Initializng an array with null values in Javascript

Can you explain why this Javascript code: var myArray = new Array(3); does not produce the same result as: var otherArray = [null, null, null]; ? Keep in mind that (myArray == otherArray) returns false. Additionally, is there a way to create an ...

When utilizing the React API Fetch, there may be instances where not all data is returned. However

Having some trouble with my FetchData class. I am receiving a list of data, but it's in an array format. When I try to access specific values like countries: data.Countries[0], I can get individual values based on the index. However, what I really wan ...

The issue with the datatable row button functionality is not functioning as expected within the

I am facing an issue with my Jade Template code where I am trying to trigger a JavaScript function when a button is clicked on each row. Despite following the documentation for DataTables and Jade, I am unable to figure out what mistake I am making. It see ...

It appears that attempting to generate a vector with more than 25 elements in Julia may result in an

I encountered this issue on Julia versions 1.10.2 and 1.10.4. To replicate the error, simply start Julia in the command prompt and define a variable test=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ...

jQuery and AJAX create an interactive form that adapts to user input

I'm facing a little issue because I'm not sure how to proceed with this. Imagine I have this HTML form: <form action="#" method="post"> <select name="change_reason" required> <option value="">Please select</option> ...