Filter and return only specific sections of the matched object

How can I selectively return only a specific part of the matched object while using the filter method on a list?

For example:

let comments = [{
    "postId": 6,
    "status": "ACTIVE",
    "id": 28,
    "name": "quo voluptates voluptas nisi veritatis dignissimos dolores ut officiis",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6b48988889fa69489958f8887c8899481">[email protected]</a>",
    "body": "voluptatem repellendus quo alias at laudantium\nmollitia quidem esse\ntemporibus consequuntur vitae rerum illum\nid corporis sit id"
  },
  {
    "postId": 6,
    "id": 29,
    "status": "INACTIVE",
    "name": "eum distinctio amet dolor",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a406f646463646d79555a657f78665794a6f7863696b24686370">[email protected]</a>",
    "body": "tempora voluptatem est\nmagnam distinctio autem est dolorem\net ipsa molestiae odit rerum itaque corporis nihil nam\neaque rerum error"
  }
];

comments.filter((ob, i) => {
  return ob.status == "ACTIVE" && ob.id
})

In this scenario, the filter function applied to comments returns the matching object. However, my goal is to retrieve only a list of id.

Answer №1

filteredComments = comments.filter((comment, index) => {
  return comment.status == "ACTIVE" && comment.id
}).map(({id}) => id)

Answer №2

If you want to accomplish this task, you can utilize the map function in your code. Check out more information about how to use Map on MDN.

Take a look at the sample code below:

comments.map(function (data) {
  return data.id
});

When you run this code, it will generate an array containing all the ids present in the comments variable.

Answer №3

Here are two different approaches to solve the problem:

Utilizing map after applying filter

let comments = [{
    "postId": 6,
    "status": "ACTIVE",
    "id": 28,
    "name": "quo voluptates voluptas nisi veritatis dignissimos dolores ut officiis",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77251819190e370518041e191659180510">[email protected]</a>",
    "body": "voluptatem repellendus quo alias at laudantium\nmollitia quidem esse\ntemporibus consequuntur vitae rerum illum\nid corporis sit id"
  },
  {
    "postId": 6,
    "id": 29,
    "status": "INACTIVE",
    "name": "eum distinctio amet dolor",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c18ba4afafa8afa6b29e91aeb4b3aeb281a4b3a8a2a0efa3a8bb">[email protected]</a>",
    "body": "tempora voluptatem est\nmagnam distinctio autem est dolorem\net ipsa molestiae odit rerum itaque corporis nihil nam\neaque rerum error"
  }
];

const arr = comments.filter((ob, i) => {
  return ob.status == "ACTIVE"
}).map(ob => ob.id)

Using reduce

let comments = [{
    "postId": 6,
    "status": "ACTIVE",
    "id": 28,
    "name": "quo voluptates voluptas nisi veritatis dignissimos dolores ut officiis",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e4c717070675e6c716d77707f30716c79">[email protected]</a>",
    "body": "voluptatem repellendus quo alias at laudantium\nmollitia quidem esse\ntemporibus consequuntur vitae rerum illum\nid corporis sit id"
  },
  {
    "postId": 6,
    "id": 29,
    "status": "INACTIVE",
    "name": "eum distinctio amet dolor",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f7bd9299999e999084a8a79882859884b792859e9496d9959e8d">[email protected]</a>",
    "body": "tempora voluptatem est\nmagnam distinctio autem est dolorem\net ipsa molestiae odit rerum itaque corporis nihil nam\neaque rerum error"
  }
];

const res = comments.reduce((pre, cur) => {
  if (cur.status === "ACTIVE") {
    return [...pre, cur.id]
  } else {
    return pre
  }
}, [])


In my opinion, the first approach might be easier to comprehend.

For more information on reduce, refer to the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Answer №4

To utilize the map() function, consider using Destructing Assignment:

let users = [{
    "id": 1,
    "name": "John Doe"
  },
  {
    "id": 2,
    "name": "Jane Smith"
  }
];

users = users.filter((obj, index) => {
  return obj.id == 1
}).map(({name}) => ({name}));

console.log(users);

Answer №5

To filter out active comments based on their status and id, you can utilize the reduce method:

const result = comments.reduce((activeComments, currentComment) => {
   if (currentComment.status === "ACTIVE" && currentComment.id)
       activeComments.push(currentComment.id);
   return activeComments;
}, [])

For example:

let comments = [{
  "postId": 6,
  "status": "ACTIVE",
  "id": 28,
  "name": "quo voluptates voluptas nisi veritatis dignissimos dolores ut officiis",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="184a77767661586a776b71767936776a7f">[email protected]</a>",
  "body": "voluptatem repellendus quo alias at laudantium\nmollitia quidem esse\ntemporibus consequuntur vitae rerum illum\nid corporis sit id"
},
{
  "postId": 6,
  "id": 29,
  "status": "INACTIVE",
  "name": "eum distinctio amet dolor",
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="165c7378787f787165494679636479655673647f757738747f6c">[email protected]</a>",
  "body": "tempora voluptatem est\nmagnam distinctio autem est dolorem\net ipsa molestiae odit rerum itaque corporis nihil nam\neaque rerum error"
}
];

const result = comments.reduce((activeIds, comment) => {
  if (comment.status === "ACTIVE" && comment.id)
    activeIds.push(comment.id);
  return activeIds;
}, [])

console.log(result);

Answer №6

It seems unnecessary to use two separate loops for this task. Instead, you can achieve the same result with just one loop using a for of loop like in the following example:

let comments = [{
    "postId": 6,
    "status": "ACTIVE",
    "id": 28,
    "name": "quo voluptates voluptas nisi veritatis dignissimos dolores ut officiis",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="792b16171700390b160a10171857160b1e">[email protected]</a>",
    "body": "voluptatem repellendus quo alias at laudantium\nmollitia quidem esse\ntemporibus consequuntur vitae rerum illum\nid corporis sit id"
  },
  {
    "postId": 6,
    "id": 29,
    "status": "INACTIVE",
    "name": "eum distinctio amet dolor",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eba18e858582858c98b4bb849e998498ab8e9982888ac5898291">[email protected]</a>",
    "body": "tempora voluptatem est\nmagnam distinctio autem est dolorem\net ipsa molestiae odit rerum itaque corporis nihil nam\neaque rerum error"
  }
];

const matchedCommentsIds = []
for (const {status, id}of comments) {

  if (status == "ACTIVE" && id){
    matchedCommentsIds.push(id)
  }
}

console.log(matchedCommentsIds)

https://i.sstatic.net/xmCE2.png

If we resort to using the filter and map functions, we would have to iterate through the array twice unnecessarily.

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

Creating a dynamic array within a structure in C++

Having some trouble allocating an array of structs within a struct. Can you check out my code below? struct t_nd { double info; }; struct t_nwork { struct t_nd *items; }; ...

Instructions on sending search fields by pressing the enter key

Developing my application in React.tsx, I have a menu window that consists of numerous div elements with input fields, checkboxes, and select elements. Upon clicking the submit button, a list of results with user-selected filters appears. As an additional ...

Is it necessary for the raycaster to be positioned within the render() function at all times?

Looking to capture the mouse double-click event's location and generate a 3D object in that spot within the scene. My understanding is that the raycaster, which is in the render() function, constantly updates the mouse location. I am interested in ha ...

Sending an AJAX request to a REST service in order to submit the information captured in an HTML form

<html> <body> <form method="POST"> <label>username</lable> <input id="username" name="username" type="text"> <label>emailid</lable> <input id="emailid" ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

"Exploring the world of Node.js with Three.js: A comprehensive guide

In our Node.js class, we've kicked off our exploration of this technology with an interesting assignment. The task is to delve into a chosen Node.js module, grasp the fundamentals, and showcase it to the rest of the class. As I was scouring through li ...

Substitute placeholders in array with information using a loop

I have a question regarding implementing an autosort feature in JavaScript. I want my page to automatically sort data rows based on different time intervals selected by the user through checkboxes. The data updates every 3 seconds, and the autosort functio ...

Is it advisable to add my project source files in the npm distribution package?

Many projects choose to include their source code in the NPM distribution package bundle. One example is React, which has unminified/unbuilt JavaScript files in a lib folder, as well as built files in a dist folder. Is this beneficial practice? On the do ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

activate the div on ng-click

In my HTML code, I have a section enclosed in a div tag that is used to display a form for replying to comments. <div class="box-body showmycomments"></div> <div class="box-footer showmycomments"></div> Additionally, there is an ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Issue: [$injector:unpr] encountered while configuring routing

Looking to implement a basic authentication system for my angularjs application. The problem arises when I try to debug the app.js on line 20, and an error is displayed: Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr?p0=configPr ...

Encountering a CSS problem while attempting to design a section featuring a background image

On this page, I have the login bar on the right and the footer at the bottom. I want a div to sit in the area currently occupied by the background image and fill it with the full background image. Currently, everything is wrapped in a wrapper and the back ...

Incorporating a secure and personalized "tracking code" feature into a PHP web application

My web application is built using vanilla PHP and MySQL, allowing registered users to create personalized profile pages. I want to implement a textarea form field in the control panel for users to input their custom tracking code (such as Facebook Pixel o ...

Tips for personalizing error messages for the "required" field by utilizing a dictionary feature on VeeValidate in Vue.Js

I am trying to update the error message that appears when an input field with the "cpf" rule is left empty (meaning it does not meet the "required" rule). I believe using the "dictionary method" with custom messages is the solution, but I am struggling to ...

Inspect JavaScript files on your mobile or tablet device

Looking to view JavaScript code on a mobile or tablet device? With Chrome browser, simply click the F12 key and navigate to the sources tab. ...

In C++, transferring a 2D array as a reference parameter in a function call

void generate() will instantiate a 2D array with dimensions determined at runtime and pass it to alter() by reference. void alter() will modify the contents of the array. .h file: void alter(______, int mySize); void generate(int size); in .cpp file: ...

Next and previous buttons on Bootstrap carousel are not functioning properly with certain pop-up modals in a React application

Bootstrap Carousel Implementation for Viewing Photo Groups Utilizing a Bootstrap Carousel, I have created a feature to display different groups of photos. Each group of photos can be clicked on to open a Modal, showcasing all the images in a carousel form ...

Even though `return false` is called, the line of code is still being executed

I am looking for a way to validate user input details before submitting them to the database. I have multiple tabs in a form and one common save button that triggers a save function when clicked, as shown below; $scope.saveFn = function () { $("#activ ...

Passing multiple variables to another page via AJAX

As I develop a website, I encountered an issue with resetting the password script on a specific page. To resolve this, I am utilizing AJAX to pass both the old and new passwords while aiming to display the outcome on the same page. The code snippet for th ...