Eliminate all key-value pairs from an array of objects except for the specified key-value pair

I've got an array filled with objects

const myArr = [
  {k1: 1, k2: 1, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}, 
  {k1: 1, k2: 2, k3: 3, k4: 4}
]

I'm attempting to filter these objects, although I don't necessarily have to use the "filter" method.

const filteredObj = myArr.filter(item => item.k2 === 1)

However, I only want to retain one specific key-value pair. For example,

console.log(myArr) => {k2: 1}

Answer №1

Implement the use of map() along with object destructuring and property shorthand syntax in the following code snippet:

const array = [
  {key1: 1, key2: 1, key3: 3, key4: 4}, 
  {key1: 1, key2: 2, key3: 3, key4: 4}, 
  {key1: 1, key2: 2, key3: 3, key4: 4}, 
  {key1: 1, key2: 2, key3: 3, key4: 4}
]

const filteredObject = array.filter(item => item.key2 === 1).map(({key2}) => ({key2}));

console.log(filteredObject);

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

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...

What steps should be taken to ensure that the onmouseover and onmouseout settings function correctly?

The Problem Currently, I have a setup for an online store where the shopping cart can be viewed by hovering over a div in the navigation menu. In my previous prototype, the relationship between the shoppingTab div and the trolley div allowed the shopping ...

What is the best way to incorporate an if else condition using the <?php if($loggedin): ?> statement within JavaScript code to display a button push or pop response from the server side?

I would like to verify this php if condition code ''<?php if($loggedin) : ?>'' inside JavaScript code in order to display one of the buttons, either push or pop. I want to keep this button hidden from the client side by embedding ...

Discovering elements using Selenium in a JavaScript popup box

The issue at hand is rather straightforward. I am faced with the task of clicking on an element within a popup that has been dynamically generated by JavaScript code. The challenge arises as the page is solely accessible in Internet Explorer and the elemen ...

Updating React state from another component - using useState

How can I efficiently update this state in React so that it changes when a specific button is clicked within the <FirstPage /> component? I'm struggling with finding the best approach to accomplish this. Any suggestions? const SignUp = () => ...

Unable to fetch information from Grid to a new window with Form in Extjs 4

Having trouble transferring data from a grid to a form in Extjs 4. I'm attempting to pass the field vid to the form for testing purposes, but I'm unable to do so. Despite trying several examples and ideas, I can't seem to make it work. The ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

Components undergo a style transformation with Material UI

I've noticed that every time I render the component, the styles keep changing. import React from 'react'; import FormControl from '@material-ui/core/FormControl'; import MenuItem from '@material-ui/core/MenuItem'; im ...

What is the process for implementing a click event and accessing the DOM within an iframe using react-frame-component?

I am working on using the react-frame-component to create an iframe. I am trying to bind a click event on the iframe and retrieve the DOM element with the id of "abc" inside the iframe. Can anyone guide me on how to achieve this? The code snippet provided ...

javascript unusual comparison between strings

I am working on an ajax function that is responsible for sending emails and receiving responses from the server in a JSON format with type being either success or error. $("#submit_btn").click(function(event) { event.preventDefault(); var post_d ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

Listening for time events with JQuery and controlling start/stop operations

I recently developed a jQuery plugin. var timer = $.timer(function() { refreshDashboard(); }); timer.set({ time : 10000, autostart : true }); The plugin triggers the refreshDashboard(); function every 10 seconds. Now, I need to halt the timer for ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Create a dynamic image showcase using PHP or JavaScript

So I have a large collection of car photos organized in a structure similar to this (this is just a fictional example to illustrate my idea): Cars > Audi > Sports cars > '5 pictures' Cars > Audi > Family cars > '3 pictur ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

Utilizing a JavaScript variable to fetch a rails URL: A comprehensive guide

One interesting feature I have is an image link that has a unique appearance: <a href="#user-image-modal" data-toggle="modal" data-id="<%= image.id %>"><img class="user-photo" src="<%= image.picture.medium.url %>" alt="" /></a&g ...

Retrieving user information from Firebase with Promise instead of Observable

In my React project, I successfully implemented the Observer pattern to retrieve user data from Firebase. This approach made perfect sense and here is a snippet of the code where I utilized the observer pattern: unsubscribeFromAuth = null; componentDidMou ...

What is the best technology to implement for a band website design?

I'm in the process of creating a website for my friend's band, and I need some creative input. The site will feature minimal content such as a bio, news, and embedded audio/visual material. While my web development skills are decent, I'm loo ...