How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys.

Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you.

obj = {
  name: ...,
  id: ...,
  description: ...,
  blah: ...,
  bloop: ...,
  blip: ...,
  ... and 12 others
}

However, your only focus lies on certain attributes like id and name.

I'm aware of object destructuring that allows me to extract these specific attributes into separate variables.

const { id, name } = obj

Is there a way to convert the original obj into a new object resembling the following without manually accessing each key-value pair?

newObj = {
  id: ...,
  name: ...
}

I'm interested in discovering if there's a succinct one-liner solution that can be utilized within a map function to transform an entire array of such objects.

Answer №1

To extract only the desired attributes, simply destructure them and leverage shorthand notation for creating a new object.

finalResult = data.map(({ value, label }) => ({ value, label }));

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

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Am I going too deep with nesting in JavaScript's Async/Await?

In the process of building my React App (although the specific technology is not crucial to this discussion), I have encountered a situation involving three asynchronous functions, which I will refer to as func1, func2, and func3. Here is a general outline ...

Is it better to Vuex - manipulate store item twice, trigger new items, or perform transformations within components each time they are mounted?

I am considering performing two separate transformations on a single, large store item and then saving the results as two new store items. For instance: setEventsData: (state, data) => {...} // main huge master object // perform transformations on it an ...

JavaScript - Retrieve events from an element and assign them to a keyboard button

I am currently curious about the following scenario: Suppose I have an element with a particular event. For example, when this element is clicked, it triggers alert('clicked); Now, my question is: Is there a way to capture the events of this element ...

When using LWP::Simple::get, the URL that typically functions in a browser may not yield the desired

#!/usr/bin/perl use strict; use warnings; use JSON qw( decode_json ); use LWP::Simple; my $cavirtex = get('https://www.cavirtex.com/api2/orderbook.json?currencypair=BTCCAD'); print $cavirtex; After running the code, I encountered the following ...

Tips for transferring information from one php page to another php page via ajax

I am attempting to retrieve data from one PHP page and transfer it to another page through the use of Ajax. JavaScript : $.ajax({ url: "action.php", success: function(data){ $.ajax({ url: "data.php?id=data" ...

The Canvas Clear function is malfunctioning; the items in the array are not being deleted

Even after being deleted from the array, the squares are still drawn. Shouldn't they disappear when removed from the Array? Does the array not update within the go function? Javascript: var canvas; var ctx; $(document).ready(function(){ $("#t ...

Laravel Mix fails to recognize VueJs integration in Laravel

Having an issue setting up VueJs with laravel 5.7 and mix where it keeps saying VueJs is not detected. I've already executed the npm install command. Below is my welcome view: <!doctype html> <html lang="{{ str_replace('_', '- ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Ways to navigate a JSON file and automatically populate an ImageView based on the JSON data

Hello, I need help figuring out how to dynamically load ImageView based on the data received from JSON. Sometimes I receive 8 images to display, other times it's 17. The challenge is loading the correct number of ImageViews based on the JSON data. Cur ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Javascript: What is the best way to narrow down search results using multiple values, regardless of the sequence in which they are entered?

React: How can I improve search result filtering to accommodate multiple values (irrespective of word order)? Example: I want to search for the title of a document using variations like "phone repair process," "repair phone process," or "process phone repa ...

Creating custom markers with an API in Vue-2-Leaflet

I'm having trouble displaying markers using an API. I can retrieve the data from the API and store it in a variable, but for some reason the markers aren't showing up when I try to display them using a v-for loop. Any assistance would be greatly ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

Having difficulty coming back from a promise catch block

I'm struggling to populate a menu list from my PouchDB database because I am unable to retrieve anything within the promise that is executed after calling get on the db. Below is the code in question: <MenuList> {this.populateSavedClues()} ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Attempting to save a dictionary as a variable

myList = getData(results) print("Subscribers: " + myList['items'][0]['statistics']['subscriberCount']) I am attempting to assign the results to a variable in order to extract and display only a specific part of the outcome. ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Is there a way to stop the execution of myFunc after it has been performed 5 times using clearInterval?

This code is designed to notify online shoppers that they need to choose a color from a dropdown menu before adding an item to their shopping cart. If no color is selected, the text will blink to alert them. How can I modify this code so that the blinking ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...