Transforming individual properties within a collection of objects to create a new object

In a scenario where there are two different arrays

let first = [
    { name: 'abc', num: 123, isPresent: true }, 
    { name: 'xyz', num: 456, isPresent: false }]

let second = []

What would be the best way to loop through the first array and extract only the name and isPresent values to create a new array like this?

second = [{ name: 'abc', isPresent: true }, {name: 'xyz', isPresent: false }]

Answer №1

If you want to generate a new array filled with the outcomes of running a specific function on each item in an existing array, consider utilizing Array.prototype.map() along with the concept of Destructuring assignment:

let first = [
    { name: 'abc', num: 123, isPresent: true }, 
    { name: 'xyz', num: 456, isPresent: false }]

let second = first.map(({name, isPresent}) => ({name, isPresent}));
console.log(second);

Answer №2

If you want to extract specific fields from an array, you can utilize the map function in JavaScript.

let originalArray = [
  { fruit: "apple", quantity: 5, organic: true },
  { fruit: "banana", quantity: 10, organic: false },
];

let extractedArray = originalArray.map(({ fruit, organic }) => ({ fruit, organic }));

console.log(extractedArray);

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

Ways to incorporate scroll buttons on both sides for dynamically generated tabs

When the number of generated tabs exceeds a certain limit, they start appearing on the next line and it looks odd. I want to implement a right and left scroll option for better navigation. However, being new to scripting, I am unsure about how to include t ...

React Redux fails to dispatch an action

Recently, I attempted to integrate Redux into my React application. I created a container called SignIn that instantiates a mapDispatchToProps and connects it to the component. The SignIn component renders a sub-component called SignInForm (code provided ...

"Despite using vue.js mounted function, my data remains unchanged after making asynchronous calls to

After trying to find a solution on the internet for my specific case, I decided to call data from firebase using this line of code: this.$store.dispatch('getConsumptionFromFirebase') However, I encountered an issue where the mounted() functio ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

Setting up anchor tags with dynamically changing href values does not trigger a get request

I seem to be facing an issue that I can't quite pinpoint. Essentially, I am retrieving data from my database to populate an HTML page and dynamically assigning href values to some anchor tags. However, upon clicking on the links, the page simply reloa ...

The fullcalendar function 'refetchEvents' does not initiate a request for new data

Here is the code snippet you can refer to: Whenever I modify the selection in the "eventSelect" dropdown menu, it consistently triggers the following post request: POST: http://example.com/events.php end: 2017-02-25 start: 2017-02-20 state: all I am ...

Issue with rendering 3D text in a three.js environment

Why isn't the text 'Hello three.js!' showing up in my scene when using TextBufferGeometry? It was working fine with BoxGeometry, so I must be missing something. var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, wi ...

Identifying Symbian OS gadgets using JavaScript or CSS

I've been working on enhancing a website for Symbian OS, and while using media queries, I've noticed that Symbian OS doesn't support them. Is there a method to identify if the website is being accessed from a Symbian device and then load spe ...

Which library does stackoverflow utilize to showcase errors (utilizing Bootstrap popover for error help-block)?

Currently, I am using bootstrap's has-error and help-block classes to display validation error messages in my form. However, I find the error message display in Stackoverflow's Ask Questions Form to be very appealing. Are they using a specific js ...

Numerous toggles paired with various forms and links

I am currently facing an issue with toggling between forms on my website. Although the toggle functionality works fine, I believe I may have structured the steps in the wrong order. My ideal scenario is to display only the 'generating customer calcul ...

How can I place the current date inside a red dashed box with text using JavaScript?

Let's Solve This: The date currently appears in the top left corner without any special formatting. My goal is to make it bold, red, and encased in a dashed-red border. I have identified the element by its ID "datetext", corresponding to a "p" tag w ...

In the world of JavaScript and JQuery, there exists a concept similar to "require_once" that

I have created a JavaScript class, but I am encountering issues with making an Ajax request in the constructor function. I want the response from the Ajax request to populate my object's attributes, but it is not working as expected. Can someone help ...

What is the best way to evaluate the PC names in a multiobject array against those in a single object array simultaneously?

Greetings, fellow Powershell newcomer! I am attempting to cross-reference the computer names retrieved using my $getADComp function (CN) with those in the $WSUSArr output. My goal is to identify which PCs are present in WSUS but not in AD, and vice versa ...

Asynchronous Function Implementation of Cookies in JavaScript

Here's my query: Is it possible to store a cookie within an async function? For example, creating a cookie from this fetch and then accessing it later within the same function while the fetch continues to update the value each time the function is ex ...

What is the best way to target and focus on all class fields that have a blank value?

<input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="3"> <input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="4"> Is there a way to target o ...

What is the best way to retrieve the value of a URL parameter using javascript?

I need help extracting the value of a specific parameter from a list of URLs. Here are some examples: http://example.com/#!/dp/dp.php?g=4346&h=fd34&kl=45fgh&bl=nmkh http://example.com/#!/dp/dp.php?h=fd34&g=4346&kl=45fgh&bl=nmkh ht ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

Dynamically filtering and mapping arrays in JavaScript

Here is an example of a JSON structure: [ { "part": "LM", "section": "021", "column": "001", "description": "Description of activity/liability", "typ ...

Exploring the Open method in AJAX and its impact on synchronicity

I am in the process of creating a webpage that utilizes the openweathermap.org API. However, I am encountering an issue when making an AJAX call and trying to access the API using weather.open(blah, blah, true). function executeWeatherCity(cityName){ ...

How can you implement a resource response approach in Express.js using an API?

As a newcomer in my journey with expressjs, I'm currently exploring its functionalities. In my controller, I've structured the response as follows: .... res.json({ 'data': { 'user': { 'id': us ...