What is the best way to extract a specific portion of an object array into a new array?

I am working with an Object array containing product information:

let products = [{ code: 'a', num: 1 }, { code: 'b', num: 2 }];

My goal is to extract the codes from this array: ['a', 'b'].

Currently, I'm achieving this using lodash:

let codes = [];
_.forEach(products, (product) => {
  codes.push(product.code);
});

However, I'm wondering if there's a more efficient way to accomplish this task. Any suggestions?

Answer №1

Sure thing, a completely JavaScript-based approach is available:

const productCodes = products.map(item => item.code);

Answer №2

If you need to extract specific data from an array of objects, consider using the map() method in lodash:

let codes = _.map(productsArray, 'code');

let productsArray = [{ code: 'x', num: 10 }, { code: 'y', num: 20 }];

let extraction = _.map(productsArray, 'code');

document.write('<pre>' + JSON.stringify(extraction, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

Answer №3

Implement vanilla JavaScript's Array.map method to transform an array

var arr = [{ code: 'a', num: 1 }, { code: 'b', num: 2 }];

var newArr = arr.map(function(obj){
  return obj.code;

})

console.log(newArr)

   var arr = [{
     code: 'a',
     num: 1
   }, {
     code: 'b',
     num: 2
   }];

   var newArr = arr.map(function(obj) {
     return obj.code;

   })

    console.log(newArr)

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

A simple guide on passing a variable from Node.js to the view

Currently, I am delving into the world of Node.js and encountering a hurdle in sending a variable from app.js to index.html without relying on Jade or any other template engine. Below is my implementation in app.js: var express = require("express"); var ...

What is the best way to add JSON data into a table on a WordPress site?

I'm working on a WordPress custom page that generates JSON data. I would like to know how I can insert this data into a custom table within the WordPress database. Can someone please guide me on how to achieve this? {"schedule":[{"day":"2017-10-25" ...

Leveraging PHP for populating JavaScript variables

I am currently working on populating a Drop-Down menu from a csv file stored on a network share. So far, I have successfully managed to populate the options when the file is in the wwwroot folder. However, I am now encountering an issue with referencing a ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

Connection between mapStateToProps and mapActionsToProps failing to trigger in react component

I am facing an issue with my component (SearchFilter.js) where the connect method is not triggering mapStateToProps and mapActionsToProps on export. The problem is that mapStateToProps is not firing at all -- no props (neither state nor actions) are showi ...

What is the most effective way to transfer data from a Django view to JavaScript for execution on a webpage?

I recently learned that it may not be the best practice to retrieve data from a Django view and utilize that information within the Javascript loaded on the page. For instance, if I am developing an application that requires additional data to be fetched ...

The div functions seem to stop working properly after they have been multiplied

Initially, I use JavaScript to multiply the div but then encounter issues with the function not working properly. function setDoorCount(count) { $('.doors').html(''); for (var i = 0; i < count; i++) { var content = " ...

Make sure to verify the existence of the data before trying to access it to avoid encountering an

Is there a more efficient way to handle data retrieval and avoid potential errors in React when accessing information from an API? The current code, although functional, appears to be quite repetitive. renderComicList() { var detail = this.props.ser ...

Implementing sliders for interactive functionality with an HTML table

I need to implement sorting and sliding features on an HTML table using jQuery. Sorting has already been achieved by utilizing the DataTable.js jQuery library. The challenge now is to incorporate a slider into the table, with all subject columns being scro ...

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

What is the reason behind TypeScript indicating that `'string' cannot be assigned to the type 'RequestMode'`?

I'm attempting to utilize the Fetch API in TypeScript, but I keep encountering an issue The error message reads: Type 'string' is not assignable to type 'RequestMode'. Below is the code snippet causing the problem export class ...

Creating a personalized JSON object using the outcome of a GROUP BY statement in PHP

I am currently attempting to retrieve a JSON object from a PHP script. Here is the code I have written so far: <?php $connection=pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=root") or die("Can't connect to database ...

Sending a Compressed File to Server Using AJAX

I've successfully created a php file that takes a zip file, unpacks it, and places it at the specified path on my server. While it works perfectly with a standard form that calls the php file in the action, I've been struggling to make it work w ...

How to effectively utilize string concatenation in AngularJS for the src attribute of an HTML img

I am currently utilizing the YouTube API v3 to extract videos from a playlist. Each video JSON object includes a unique videoId. My aim is to use this videoId to construct the src attribute in the img element using Angular. Here's my current setup: ...

What is the best way to export several 'sub-components' from a single node.js module?

Here's what I mean by exporting 'sub-modules': var fibers = require('fibers'); // this is functional as the 'main' module var future = require('fibers/future'); // also operational as a 'sub' ...

Adjust the position of elements to prevent overlap

I'm facing a problem with elements overlapping on my website. The navbar is sticky, meaning it slides down the page when scrolling. Additionally, I have a "to-top" button that automatically takes you to the header when clicked. I want the "to-top" but ...

Setting URL parameters dynamically to the action attribute of a form using JavaScript code

I'm having trouble posting Form data to my Server. I am dynamically setting the element and its URL parameters for the action attribute, but it seems like it's not recognizing those attributes. Can you help me figure out what I'm doing wrong ...

What is the most efficient method for transferring structs to an array in C# quickly and with minimal clutter?

A structure called float4x4 holds 16 floats like this: struct float4x4 { public float M11; public float M12; public float M13; public float M14; public float M21; public float M22; public float M23; public float M24; public float M ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Acquiring the assigned class attribute

I have an image that triggers ajax requests when clicked. To pass a variable from $_GET[] to my onclick function, I came up with the following solution: <img id="img1" class="<?=$_GET['value']"?> /> and using jQue ...