Retrieving data from a nested array within an array of objects using JavaScript

Below is an example of an array object:

const data =  [
    {
      name: "A",
      values: [
        {
          name: "PASS",
          value: 36,
        },
      ],
    },
    {
      name: "B",
      values: [
        {
          name: "PASS",
          value: 144,
        },
      ],
    },
    {
      name: "C",
      values: [
        {
          name: "PASS",
          value: 144,
        },
                {
          name: "FAIL",
          value: 256,
        },
      ],
    }]

I want to filter out the PASS objects from this data and create a new object with simplified structure as shown below:

[
 {
   name: "A",
   value: 36,
 },
 {
   name: "B",
   value: 144,
 },
 {
   name: "C",
   value: 144,
 }
] 

I attempted to achieve this using the code snippet below but encountered issues:

sorted_obj = {}
data.map(item => {
item.values.map(registry => {
  if(registry.name === 'PASS'){
    sorted_obj.push({item.name:registry.name.value})
  }
})
})

Please advise on how I can correct my approach or suggest a better solution. Thank you for your assistance.

Answer №1

Employing the use of Array.flatMap() is an effective way to iterate through the data array. By implementing a filter on the values, we can selectively include only the items with "PASS" in their name. Subsequently, we should map these passed items while utilizing the name attribute from the parent object:

const data = [{"name":"A","values":[{"name":"PASS","value":36}]},{"name":"B","values":[{"name":"PASS","value":144}]},{"name":"C","values":[{"name":"PASS","value":144},{"name":"FAIL","value":256}]}]

const result = data.flatMap(o => 
  o.values.filter(v => v.name === 'PASS')
  .map(v => ({ 
    name: o.name,
    value: v.value,
  }))
)

console.log(result)

Answer №2

const info = [
    {
      color: "Red",
      values: [
        {
          type: "Large",
          quantity: 10,
        },
      ],
    },
    {
      color: "Blue",
      values: [
        {
          type: "Medium",
          quantity: 20,
        },
      ],
    },
    {
      color: "Green",
      values: [
        {
          type: "Small",
          quantity: 5,
        },
        {
          type: "Medium",
          quantity: 15,
        },
      ],
    }
];
    
const sorted_items = [];
info.map(item => {
  item.values.map(entry => {
    if(entry.type === 'Medium'){
      sorted_items.push({color: item.color, quantity: entry.quantity})
    }
  });
});
console.log(sorted_items);

Answer №3

Simply use a for...of loop along with object destructuring to achieve this task.

const data=[{name:"A",values:[{name:"PASS",value:36}]},{name:"B",values:[{name:"PASS",value:144}]},{name:"C",values:[{name:"PASS",value:144},{name:"FAIL",value:256}]}];

const out = [];

// Iterate through each object in the data array and extract
// the name and values properties
for (let { name, values } of data) {

  // Retrieve the value from the object within values that has a name of PASS
  const value = values.find(({ name }) => name === 'PASS').value;

  // Add a new object with these properties to the output array
  out.push({ name, value });
}

console.log(out);

Answer №4

This is how I like to approach things - straightforward, concise, and efficient.

const info = [{"name":"X","values":[{"name":"YES","value":21}]},{"name":"Y","values":[{"name":"TRUE","value":98}]},{"name":"Z","values":[{"name":"YES","value":56},{"name":"NO","value":77}]}]

const outcomes = info.map((results)=>({name: results.name, value: results.values.find(entry => entry.name === 'YES').value}))

console.log(outcomes)

Answer №5

For improved performance considerations, my choice would be to utilize Array.prototype.reduce() over Array.prototype.flatMap(). Here is an example:

const src = [{name:"A",values:[{name:"PASS",value:36}]},{name:"B",values:[{name:"PASS",value:144}]},{name:"C",values:[{name:"PASS",value:144},{name:"FAIL",value:256}]}]
    
const result = src.reduce((acc, {name, values}) => {
  const pass = values
    .filter(({name:_name}) => _name === 'PASS')
    .map(({value}) => ({name, value}))
  acc.push(...pass)
  return acc
}, [])    

console.log(result)
.as-console-wrapper {min-height:100%;}

Answer №6

This method begins by extracting the values and then flattening them to form a unified list of all values. Subsequently, this list can be refined using the Array.filter technique.

Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Filter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

const data =  [
    {
      name: "A",
      values: [
        {
          name: "PASS",
          value: 36,
        },
      ],
    },
    {
      name: "B",
      values: [
        {
          name: "PASS",
          value: 144,
        },
      ],
    },
    {
      name: "C",
      values: [
        {
          name: "PASS",
          value: 144,
        },
                {
          name: "FAIL",
          value: 256,
        },
      ],
    }];
    
    const allNestedValues = data
    .map(obj => obj.values.map(value => ({...value, objName: obj.name}))) //extract the nested values
    .reduce((acc, curr) => [...acc, ...curr], []); //create a flattened list of values
    
    const passingNestedValues = allNestedValues
    .filter(value => value.name === 'PASS') //filter to allow just PASS
    .map(value => ({name:value.objName, value:value.value}))//extract desired properties
    console.log(passingNestedValues);

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 angular variable is being updated, but the tweet embed code surrounding it is not being refreshed

I've been working with Angular to loop through an array of tweet ids and display them on the page using Twitter's embed code. The issue I'm facing is that although the variable gets updated, the twitter embed remains static. Here's a gl ...

Supabase's newly uploaded audio blobs are experiencing difficulties when it comes to

I've integrated Supabase storage for storing audio blobs. After retrieving the blob from an API call, it is uploaded successfully to the storage bucket. However, when attempting to play the audio file, nothing happens and the duration shows as 0:00. S ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...

Issue Encountered with FabricJS: Unable to Execute 'drawImage' with Image Subclass

I'm working on a project that requires me to add images of different types to a canvas, save them as JSON, and then load them again. The unique property needed for each type is simply the differentiation in type. To achieve this, I have created a new ...

I am experiencing issues with staying logged in while using Passport and sessions. The function "isAuthenticated()" from Passport continuously returns false, causing me to not remain logged in

I have been working on implementing authentication with Angular, Passport, and sessions. I can successfully create a new user and log in, but I am facing an issue: Problem Every time I check if the user is authenticated using Passport's isAuthentica ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Is it possible to use jQuery's .attr method to change the href attribute if a certain text is contained within a DIV

(Twitter) I'm struggling with how to incorporate the .attr method at the start of links/A/href when the selected element contains specific words: $(".tweet:contains('government','Anonymous')").each(function(){ $old_url = $(thi ...

Sending postMessage during the beforeunload event does not work as expected

When postMessage() is triggered within the beforeunload window event in an Ionic 2 browser, I've noticed that the message doesn't make it to the parent. However, if the same message is sent during the unload or load event, it is received successf ...

Trouble arises when rendering nested components in React Router 4

My issue lies with implementing React Router 4 while utilizing "nested" routes. The problem arises when one of the top routes renders a component that matches the route, even though I do not want it to be rendered. Let me provide the relevant code snippets ...

Ways to modify the color of a container's border by interacting with radio buttons through JavaScript

I'm currently facing a challenge with creating a settings dropdown menu that allows users to select different themes. Each theme is supposed to modify the background color and border color, but I have successfully implemented only the background color ...

The length of the HTTP response in Angular is not defined

Currently, I am utilizing Angular in conjunction with jQuery Mobile to develop multiple pages, but I have encountered an obstacle when using the $http service to connect to my JSON requests. While populating a few arrays with functions and successfully ret ...

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

Tips for triggering a function when the range slider is adjusted

I'm looking to trigger a function whenever a user changes a range slider in my Vue.js project, and I also need to pass the new value to that function. The code snippet below shows what I have so far. <div cla ...

Having trouble determining why the design is not displaying correctly

I'm currently working on a calendar webpage, and everything looks perfect until I add the new JavaScript element. Suddenly, the numbers in the first row start behaving strangely. I've tried to troubleshoot but can't seem to figure out what&a ...

Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

Guide on building a multi-page application using Vue or React

I find myself a bit confused when it comes to single-page applications versus multi-page applications. While I am aware of the difference between the two, I am struggling with creating a MPA specifically. Up until now, I have built various apps using Rea ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

How to display nested arrays in AngularJs

Within my array contacts[], there are multiple contact objects. Each of these contact objects contain an array labeled hashtags[] consisting of various strings. What is the best way to display these hashtags using ng-repeat? ...

Transitioning from a multipage application to Piral: A comprehensive guide

Our organization operates several ASP.NET Core applications that are traditional multipage applications. As we develop a new portal using Piral, we want to incorporate elements from our existing applications while also introducing new modules. How can we ...