What is the best way to elegantly extract a subset array from an array of objects?

Imagine you have the following array of objects:

var myObject =
[
{A:1, B:2, C:3},
{A:4, B:5, C:6},
{A:7, B:8, C:9},
]

How would you efficiently retrieve a subset with the Y values from this array?

var subset = [ B:2, B:5, B:8 ]

Answer №1

let list = [
  {A:1, B:2, C:3},
  {A:4, B:5, C:6},
  {A:7, B:8, C:9},
];
const result = list.map(({B}) => ({B})); // [{B: 2}, {B: 5}, {B: 8}]

This code snippet utilizes an arrow function to iterate over the array, extracting the B property from each object, and creating a new object with just the B property using object property shorthand.

Answer №2

Using an arrow function with <code>map
adds a touch of elegance:

let myArray =
[
{A:1, B:2, C:3},
{A:4, B:5, C:6},
{A:7, B:8, C:9},
];
let result = myArray.map(item => ({B: item.B}));
console.log(result);

This code becomes even more sleek when you incorporate destructuring as demonstrated by Jared. :-)

Answer №3

To accomplish this task, utilize the map function

var data = [ 
  {A:10, B:20, C:30},
  {A:40, B:50, C:60},
  {A:70, B:80, C:90},
];

var result = data.map(item => { 
  return {
      B: item.B 
  };
});

console.log(result);

Answer №4

Although I may not have fully grasped the requested output notation, you can still utilize a map function:

myObject.map(item => item.Y) // Produces [2, 5, 8]
myObject.map(item => ({Y: item.Y})) // Generates [{Y: 2}, {Y: 5}, {Y: 8}]

Answer №5

If you're aiming for maximum code reusability, one elegant approach is to incorporate some currying into your functions:

const arr = [
    {X:1, Y:2, Z:3},
    {X:4, Y:5, Z:6},
    {X:7, Y:8, Z:9},
];

const get = prop => o => ({[prop]: o[prop]});
const extract = arr => prop => arr.map(get(prop));

const result = extract(arr)('Y');
console.log(result);

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

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

How can I set it up so that clicking on a specific number within the table will direct me to various pop-ups or additional tables?

// Sending an HTTP request to fetch JSON data $http({ method: 'GET', url: '/Home/GetJson' }).then(function successCallback(response) { console.log(response); $scope.jsonData = response; var data = response.data ...

Utilize a WebAPI controller to serialize a complicated JSON object

Embarking on a new journey with AngularJS and ASP.NET WebAPI, I find myself faced with the challenge of working with base tables structured as follows: CurriculumID SubjectArea CourseNumber ------------ ----------- ------------ 303 GHIJ 1 ...

Restrict the duplication of div elements with JQuery

Here is the structure I'm working with: <div class="checkmark-outer"> <div class="checkmark-33"> <div class="fa-stack fa-1x checkmark-icon"> <i class="fa fa-circle fa-stack-2x icon-background"></i> ...

Utilizing ES6 Map type in TypeScript for Angular 2 Response Data Transfer Object Definition

Is it possible to utilize the es6 Map type in an HTTP Response DTO? Let's consider an Angular 2 request: public loadFoos(): Observable<FoosWrapper> { return this.http.get("/api/foo") .map(res => res.json()); } Now, take a loo ...

How can I import an image file dynamically in Nuxt.js using environmental variables?

// env.development.js module.exports = { fileName: 'logo_dev.png' } // env.production.js module.exports = { fileName: 'logo_prod.png' } // index.vue <script> import logoSrc from '@/assets/images/' + process.env.fil ...

Guide on integrating HTML from a response into the render function in React JS

I've been doing some research but I'm struggling to find a good solution for this issue. I have a response that looks like this: "name": "another test", "description": "para hacer el aseo", &quo ...

What is the best way to send an array from Angular 6 to an ASP.NET Core API using the GET method?

When my Angular 6 app makes a request to the ASP.NET Core web API using the GET method, I want to send a list or array of unique identifiers as parameters. In return, I expect only information relevant to those identifiers to be retrieved from the API. He ...

The functionality of jhtmlarea is not functioning properly when placed within an update

Within my form, I have a jhtmlarea textarea element: textarea id="txtDigital" name="txtDigital" class="form-control" style="background-color:white; resize: vertical !important; " rows="20" placeholder="Details" ...

Sorting the output with gulp and main-bower-files (gulp-order is not functioning)

Hello, I'm a Java engineer diving into the world of Javascript for the first time. Apologies in advance if my information is lacking or incorrect! I am currently working on a gulp build script and utilizing bower to manage dependencies for my JS fron ...

Tips on converting a Java regular expression to JavaScript regular expression

Can someone assist me in translating the Java Regex code below to JavaScript Regex? (\\\p{Upper}{2})(\\\d{2})([\\\p{Upper}\\\p{Digit}]{1,30}+) I attempted using the following JavaScript Regex: ...

Building a Dynamic Web Widget with the Perfect Blend of HTML, JS,

While developing a javascript-based web widget, I am aiming to steer clear of using iframes and avoid relying on the page's CSS. It is infeasible for me to utilize custom CSS, as it defeats the purpose, and iframe integration would not present a user- ...

Incorporate a fresh attribute into each JSON object within a JavaScript array

Currently, my focus is on a react application where I am retrieving a JSON response from a specific route that consists of a collection of JSON objects. My objective now is to introduce a new field in each JSON object based on another field within the sam ...

Strategies for managing extensive data collections during server-side simulation to enhance performance on client browsers

Apologies for the unclear title. I am facing a bit of confusion with my current project. I am in the process of developing a web front-end for an academic simulation tool, which includes a C++-based simulator that is efficient for small systems but produce ...

Ajax fails to provide a response

Hey there, I'm trying to save the response from an HTML page and store the content of that page. However, every time I try, I keep getting an error message. What am I doing incorrectly? <script type="text/jscript"> var page = ""; $.aj ...

Creating a JavaScript array using XML file attributes with jQuery

Utilizing jqGrid proves to be challenging when it comes to extracting attributes from an XML file. In order to overcome this limitation, I am seeking assistance in creating an array from the XML data provided below. The ideal array format for jqGrid is as ...

Chrome not triggering the fullscreenchange event

I've been attempting to track when the browser goes into fullscreen mode. Everywhere I look, this blog is mentioned as the go-to resource on the fullscreen API. According to this SO answer, it should work. Fullscreen API: Which events are fired? B ...

What is the best way to modify specific elements within an array using the state hook?

This specific segment of code is the focus right now, Here is where my attention lies const [array, setArray] = useState( JSON.parse(localStorage.getItem("notes")) ?? [] ); And here we have the function in question, const save = () => ...

Ways to add a circular radius to a button along with a select dropdown

I am trying to enhance the visibility of the drop-down caret, but currently it is not showing up as desired. My goal is to give both the <select> and <button> elements a circular radius similar to what is shown in the image. .top-select{ ...

Angular Error: secure is not defined

Encountering the 'safe is undefined' error while interacting with HTML that has been dynamically inserted into a page via an AJAX call. For example, when selecting an option from a dropdown within this HTML, the error occurs and the dropdown rese ...