What is the best way to retrieve a specific value from a nested array that is within an array of objects

My goal is to extract a specific field value from a nested array within an object array. Using the map method, I attempted to achieve this but ended up with two empty arrays nested inside two empty objects. Though I am aware of this mistake, it indicates the direction of my thought process.

function getChildArray(item, index) {
   var x = [item.hobbies]
      return x
}

console.log(parentArray.map(getChildArray))

Here is a glimpse of my document structure:

[  
   {  
      "id":12345678900,
      "name":"Jasmin",
      "age":27,
      "hobbies":[  
         {  
            "id":1221,
            "name":"hiking",
            "when":"anytime"
         },
         {  
            "id":9865,
            "name":"eating",
            "when":"all the time"
         }
      ]
   },
   {  
      "id":223456789001,
      "name":"Joe",
      "age":35,
      "hobbies":[  
         {  
            "id":989,
            "name":"gaming",
            "when":"anytime"
         },
         {  
            "id":2355,
            "name":"online gaming",
            "when":"all the time"
         }
      ]
   }
]

I am interested in knowing how I could retrieve a list of Joe's hobbies by name only.

Answer №1

const findJoe = parentArray.find(function (person) {
    return person.name === 'Joe';
});

if (findJoe) {
    const joesHobbies = findJoe.hobbies.map(function (hobby) {
       return hobby.name;
    });
}

Alternatively, in ES6 syntax:

const findJoe = parentArray.find((person) => person.name === 'Joe');

if (findJoe) {
    const joesHobbies = findJoe.hobbies.map((hobby) => hobby.name);
}

Answer №2

Given that array.find is still unsupported in some browsers and you might not have a build tool in place, here's a straightforward ES5 solution. This approach utilizes filter and map:

var data = [{ id: 12345678900, name: 'Jasmin', age: 27, hobbies: [{'id': 1221, 'name': 'hiking', 'when': 'anytime'}, { 'id': 9865, 'name': 'eating', 'when': 'all the time' }] }, { id: 223456789001, name: 'Joe', age: 35, hobbies: [{'id': 989, 'name':
'gaming', 'when': 'anytime'}, { 'id': 2355, 'name': 'online gaming', 'when': 'all the time' }]}];

function getHobbiesByName(name) {
  return data.filter(function(person) {
    return (person.name == name);
  })[0].hobbies.map(function(hobby) {
    return hobby.name
  })
}

console.log(getHobbiesByName('Joe'))

Answer №3

Need a quick way to find an item based on a specific property and its value?

entries = [{id:3,type:'apple',colors:['red','green']},{id:4,type:'banana',colors:['yellow']}];

function getItem(prop,value){
 for(var j=0;j<entries.length;j++) if(entries[j][prop] == value) return entries[j];
 return {};
}

Let's test it out :

console.log(getItem('type','banana'));
console.log(getItem('type','banana').colors);

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

The consistent failure of the 201 status node express API is causing major

I am currently working on creating an API using Express. However, when I receive a response from the server, it shows '201 created'. The issue arises when I attempt to make an HTTP request through promises and encounter a false interpretation of ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

Tips for filtering only alpha versions, such as those labeled 1.0.0-alpha.*

Is it possible to specifically target -alpha versions of a package using semver and NPM? The common approaches like using 1.0.0-alpha.x or * do not seem to work as expected due to how the version elements are interpreted. The usage of ~1.0.0-alpha also do ...

Ways to retrieve HTML tags from a website's DOM and shadowDOM

I am currently working on a project using NodeJS where I need to extract the HTML structure of multiple websites. However, I am facing some challenges with this task. My goal is to retrieve only the HTML structure of the document without any content. It is ...

Adjust positioning of navigation when hovered over

Need help creating a cool navigation effect like this. Live example: https://hookandbarrelrestaurant.com/ Here is my code: https://codepen.io/Dhaval182/pen/rQPMoW ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

Using jQuery .each() within a PHP foreach loop: A guide

In my code, I have a foreach loop that iterates through an array of images, along with some JavaScript logic to add different classes based on whether the width is greater than or less than the height. The issue I'm facing is that the if function onl ...

Leveraging IE conditional comments for including CSS or JavaScript files can lead to an increase in the number of HTTP

Our web designer has implemented special pages for Internet Explorer by using IE-specific comments. This means that certain stylesheets are only loaded if the user is using a specific version of IE: <!--[if lt IE 7]> <link type="text/css" rel="st ...

Following the path of JavaScript function calls

As I explore my Chrome console, I find myself puzzled by the mystery of the JavaScript file that gets called when I import a file from my computer after clicking on an input file tag. It seems to happen without any clear indication of which method triggere ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

How do I make the message "document.getElementById(...) is null" become true?

When running my code, only two of the document.getElementById calls (ctx1 and ctx2) successfully get values while the others (such as ctx3) do not. How can I ensure that all elements retrieve their values without receiving an error message? Below is a snip ...

Obscure unidentified attribute within JSON error object

In my node.js console script, I am utilizing pg-promise. Node version: v0.10.38 pg-promise version: 1.1.4 A connection error occurred due to a simple misconfiguration issue that was not very informative. I would like my script to provide a detailed expla ...

Challenges with Angular directive scopes

My current task involves taking an existing template and Angularizing it. I am dealing with 3 directives: a card, a card-header, and a card-body: <card> <card-header title="My Card"> <input type="text" ng-model="userSearch" /&g ...

Looking for insights on reading and presenting XML files from a URL? Learn how to achieve this effortlessly with the power

Currently, I'm in the process of developing an innovative Android application using PhoneGap. My main objective is to dynamically present the data stored within a customized XML file hosted on my website that follows the .php format. Do you happen to ...

How can I transform JSON data into MySQL INSERT and CREATE TABLE statements?

I have a dataset in JSON format that contains details about different exercises, and I need to transfer this data into a MySQL database. Each exercise comes with attributes like name, force, level, etc. To accomplish this task, I must convert the JSON da ...

Navigating tables with jQuery using a loop and extracting data from two tables with matching row names

I am facing a challenge with a function that combines data from two tables, each containing a column named "name". How can I specify which table's name should be displayed? function createTableRow(customers) { var data = JSON.parse(customers.resu ...

Applying double encoding to the JSON value

My goal is to create a session storage for users in my Mongo db database using express-session and connect-mongo npm packages. const MongoStore = require('connect-mongo')(session); const session = require('express-session'); app.use(s ...

Remove JSON information with PHP When a button in an HTML table is clicked

I attempted to remove a JSON entry from the JSON file by clicking a button within an HTML tableview image here Here is my JSON data:[{"room_id":"1","room_type":"Duplex","room_location":"North",&q ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...