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

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

There was an issue encountered while trying to parse the yahoofinancials JSON data: An unexpected character was detected while decoding 'NaN'

Currently, I am attempting to parse a JSON file obtained from the Python library 'yahoofinancials' which fetches data from Yahoo Finance: import numpy as np import pandas as pd from yahoofinancials import YahooFinancials yahoo_financials = Yahoo ...

Attempting to save data to a .txt file using PHP and making an AJAX POST request

I have been facing an issue while trying to save a dynamically created string based on user interaction in my web app. It's just a simple string without anything special. I am using ajax to send this string to the server, and although it reaches the f ...

Ways to join two if statements together using the or operator

Below is my code attempting to check if either child elements H1 or H2 contain text that can be stored in a variable. If not, it defaults to using the parent element's text: if($(this).children('h1').length){ markerCon[markerNum] = $(th ...

changing the vertical position of an element using JavaScript

I'm currently working on a project where I have a canvas that animates upwards when a button is clicked. However, I'm facing an issue with making it go back down after the animation completes. It seems to be getting stuck and not returning to its ...

Can someone explain how to trigger a JavaScript confirmation dialog box before the page loads in an ASP.NET application?

Below is the server side code snippet I am using: protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { string confirmValue = Request.Form["confirm_value"]; if (confirmVal ...

Angular page fails to refresh upon addition or deletion of data

There's a recurring issue with my angular application where the page fails to refresh after data manipulation such as addition, editing, or removal. For example, when I add a new item to a list of subjects, it doesn't show up unless I navigate aw ...

Is it possible to include ternary in the "homepage" section of the package.json file?

When making API calls in production, they will be on the same domain as where my app is hosted, so it's necessary to include "homepage": "." in the package.json. However, when working locally from localhost, I need to make API calls to the production ...

Using jQuery to bind the "CTRL+A" key combination to exclusively selecting a specific region

My goal is to modify the CTRL+A shortcut so that instead of selecting all text, it will only select specific content within containers with a class of xyz. Unfortunately, I have not been successful in getting this functionality to work. Even attempting to ...

Regular expression that detects a phone number which does not consist of a repetition of the same digit throughout

Looking for a regex pattern to match phone numbers that do not consist of the same number repeated throughout every part. Specifically, I need it to target 10-digit phone numbers in the format (123)123-1234. I have tried using this pattern, but it's ...

Updating the color with the help of useState in React, with the use of Material

I enjoy changing the color of the icon with a click using a useState hook. I have added a click handler to the icon for this purpose. Below is the code snippet: import React, { useState } from 'react'; import './App.css'; import ThumbU ...

Transform intricate attribute of an object into a singular value

Consider a scenario where we have the two classes defined as follows: public class A { public string Name { get; } = "Johny Bravo"; public B ComplexProperty { get; } = new B(); } public class B { public string Prop1 { get; } = "value1"; p ...

Where is the best place to insert Javascript code in an HTML file - the head or body section?

I am currently developing a search engine and have implemented code to automatically redirect users from HTTP to HTTPS when they visit my site. The only question I have is whether I should place this code in the head or body section of my webpage. if(wind ...

Does the ES6 specification include .finally()?

Many Promise libraries such as Q or Bluebird have a method called .finally that is executed on both success and error. Does the ES6 promise also include this method? I haven't been able to find it. It doesn't seem to be present in Babel (6to5). ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Arrange keys in any order and retain any keys that are unfamiliar

After exploring how to sort keys in arbitrary order, a new question arises: Thanks to the assistance of oguz ismail, the ability to sort an object based on non-alphabetical keys has been achieved (accepted solution, online demo): $ echo '{ "alma": 1 ...

Animating numerous elements simultaneously during Vue component rendering

Take a look at this simple case in the following jsfiddle: https://jsfiddle.net/hsak2rdu/ I attempted to swap and animate two elements, but it didn't work as expected. When you click the toggle button in the playground, the second element quickly mo ...

The reason for setting a variable as void 0 in JavaScript

Currently, I am delving into the libraries referenced in this particular article as well as other sources. There are some truly mind-boggling concepts contained within these resources, one of which is highlighted by the following line: var cb = void 0; I ...

Dynamic Filtering of HTML Dropdown Options Based on Another Dropdown Selection

I am facing an issue with multiple HTML dropdowns. My requirement is that upon selecting an option from one dropdown, the next dropdown should get automatically populated. The data to populate these dropdowns is fetched from a database using SQL statements ...

Leveraging JSON Data for Avatars in React.js

Struggling to arrange 10 Avatars side by side for showcasing the user list. However, encountering an issue where the Avatars are being duplicated and showing incorrect initials when passing JSON data. Experimented with this in Code Sandbox linked below. h ...