Find an object within a nested object that meets a specific condition

When given an object structure like the one below:

temp = [
  {category: 'category1', branch: [{key: 'key A1', value: 'value A1'}, {key: 'key B1', value: 'value B1'}] },
  {category: 'category2', branch: [{key: 'key A2', value: 'value A2'}, {key: 'key B2', value: 'value B2'}] },
  {category: 'category3', branch: [{key: 'key A3', value: 'value A3'}, {key: 'key B3', value: 'value B3'}] },
  {category: 'category4', branch: [{key: 'key A4', value: 'value A4'}, {key: 'key B', value: 'value B4'}] }
]

The goal is to locate an object similar to

{key: 'key A3', value: 'value A3'}
when a specific value such as certainValue = 'value A3' matches within the given object.

An attempted solution has been provided in the form of code:

result = temp.map(te => te.branch.find(t => t.value === certainValue))

Unfortunately, this results in obtaining undefined values in the outcome, like so:

[undefined, undefined, {key: 'key A3', value: 'value A3'}, undefined]

Therefore, the question remains - is there a way to directly receive the exact desired result, being

{key: 'key A3', value: 'value A3'}
, without needing to iterate over the result again to remove the undefined entries?

Answer №1

If you utilize the Array#flatMap method to flatten an array, you can easily locate the desired object afterwards.

var temp = [{ category: 'category1', branch: [{ key: 'key A1', value: 'value A1' }, { key: 'key B1', value: 'value B1' }] }, { category: 'category2', branch: [{ key: 'key A2', value: 'value A2' }, { key: 'key B2', value: 'value B2' }] }, { category: 'category3', branch: [{ key: 'key A3', value: 'value A3' }, { key: 'key B3', value: 'value B3' }] }, { category: 'category4', branch: [{ key: 'key A4', value: 'value A4' }, { key: 'key B', value: 'value B4' }] }], certainValue = 'value A3',
result = temp
.flatMap(({ branch }) => branch)
.find(t => t.value === certainValue);

console.log(result);

Answer №2

Using the array method map, we can iterate through the 'temp' array and locate a specific value within the 'branch' property of each element using the find method. Finally, we use the find method again to retrieve the first non-null item that matches the condition.

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

Error: An unknown character was encountered at the beginning of the document: <!DOCTYPE html> Flutter Google Sheets

Encountering an unusual response while utilizing http in Flutter/Dart. Code that functions correctly with other APIs endpoints fails to do so here. The data at the link is formatted as jSON, not any other type. I have reviewed the following links, but non ...

Using Vue.js method passing an argument and setting a delay with setTimeout function

I'm struggling to understand why this particular code is functioning as it should. data: { return { userMinerals: 0, mineralsLimit: 1000, miners: 0, superMiner: 0, minerPrice: 10, superMinerPrice: 1 ...

Unleash the power of drag-and-drop functionality with cdkDrop

I am currently tackling a project that requires the implementation of a drop zone functionality where elements can be dragged from a list and dropped in a zone for free movement. I intend to utilize a cdkDropList for the zone due to its comprehensive list ...

Ways to transmit information from a modal to a function

Trying to figure out how to update data in an ng-grid after submitting a modal form with multiple text input controls. Should the ajax create function be called within the $scope.open controller section or resolve? $scope.open = function (size) { var mo ...

Building an Online Presentation through Imagery

While I am aware that there are numerous ways to implement a slideshow on a website, my question is centered around identifying the most widely used approach. Specifically, I am interested in knowing which method is considered the most mainstream for crea ...

Unable to output nested arrays as props in React JS to the console

Having retrieved data from a 3rd party API and stored the response in a state, I proceeded to pass an object within the response as a prop to another component. This represents the prop: { "count": 20, "games": [ { "id": 66947, "game_ ...

Emphasize the selected page number

My React application contains page numbers, but currently when a page number is clicked, it does not get highlighted or displayed in a different color. The className "text-success" can be added to make the text green. How can I dynamically add this class t ...

Is there a way to insert a space between the double quotes and colon in the dictionary's key values?

Check out my code snippet below: import json def generate_value_list(sentence): word_list = sentence.split(" ") total_number_of_words_in_the_sentence = len(word_list) value_list = [] for i in range(0, total_number_of_words_in ...

Get numerous records from two sets of data

Scenario: I currently have two JSON files stored in my mongodb database from Yelp Educational. The first JSON is for Yelp Business and the second JSON is for Reviews. JSON1: (Yelp Business) { "business_id":"tl9XIP5trlkcuSfTQqe5jg", "full_a ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...

What is the best way to iterate through a JSON object retrieved from an API in a Vue.js application?

/Hello everyone, I am struggling to figure out how to use v-for in Vue.js to create a simple HTML table from the JSON object retrieved from an API. The design is not important, I just need help with implementing v-for for this specific case. The table sh ...

Issue with SVG on tainted canvas causes IE security error when using toDataURL

In my Angular JS directive, I have implemented a feature to export SVGs to PNG. While this functionality works seamlessly in most browsers, it encounters a security error in IE. Despite my numerous attempts to troubleshoot the issue, I have been unable to ...

When transferring a CByteArray to a Bytes array, it can result in a violation of access

While investigating a landfill site, I've encountered an access violation issue caused by the following snippet of code: CByteArray baInput; ... // baInput is filled with 9804 entries BYTE* result; result = new BYTE[baInput.GetSize()]; // baInput.GetS ...

Extract specific data points from external API responses on a webpage crafted in HTML

I require assistance on how to extract individual values from an HTML page. I received a response from the PAYU payment gateway team in HTML format, but I need to retrieve specific attribute values related to the transaction details. Below is the response ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

Display or conceal a div based on the size of the screen using HTML and CSS

Hey there, I recently finished my first React Project and I’m wondering if there’s a way to hide the 'side-menu' section on mobile screens using CSS. Any suggestions? <div className='side-menu'> <SiderComponent /> < ...

Utilizing Zend JSON encoding for seamless integration with JavaScript

I'm currently working with the Zend Framework. My objective is to pass JSON data from the controller to JavaScript. I have a simple array: $array = array('a' => 1, 'b' => 2); After encoding this array into JSON format: ...

VARIABLE_NAME isn't functioning properly on the window

The code window.VARIABLE_NAME is not functioning properly and is causing the following error. Can you please provide assistance? Uncaught SyntaxError: Unexpected token. This is the code I have written: var window.testing ...

Removing users from a Socket.IO chat room using Node.js

I am facing an issue with removing users from Socket.IO when their browser is closed. The 'user' in the array 'users[]' is not getting removed or updated. Additionally, I would like to update the users on the client side as well. Can so ...

Enhancing Security with Subresource Integrity in Angular-Cli

Has anyone discovered a way to enable Subresource Integrity with Angular-CLI? I came across this GitHub Pull Request that suggests it may become a feature in the future: GitHub Pull Request. I tried to activate it on the current versions but had no luck. ...