Create a new array of objects by extracting specific properties from an existing array of objects

Consider the input array below:

const initialArray = [{name: 'john', age: 12, height: 178, likes: 'music'},
                      {name: 'mike', age: 22, height: 181, likes: 'sport'},
                      {name: 'anna', age: 18, height: 175, likes: 'sleep'},
                      {name: 'paul', age: 24, height: 170, likes: 'drink'}
                     ];

To create a new array of objects with specific properties such as name and height, you can achieve the following result:

result = [{name: 'john', height: 178},
          {name: 'mike', height: 181},
          {name: 'anna', height: 175},
          {name: 'paul', height: 170}
         ];

An attempt using map was made but it seems to have an issue:

  const result = initialArray.map((a) => {
    a.name, a.height
  });

Answer №1

To ensure proper functionality, remember to use the return keyword within curly braces or enclose the code in parentheses.

Consider exploring Destructuring assignment, a technique that allows you to specify the desired property names for resulting objects:

const myArray = [
  {name: 'alice', age: 30, height: 160, likes: 'reading'},
  {name: 'bob', age: 25, height: 175, likes: 'painting'},
  {name: 'charlie', age: 35, height: 180, likes: 'traveling'},
  {name: 'diane', age: 40, height: 165, likes: 'cooking'}
];
const updatedResult = myArray.map(({name, height}) => ({name,height}));
console.log(updatedResult);

Answer №2

It is recommended to output the object in this format:

const updatedData = originalData.map((item) => {
  return {title:item.title, price:item.price}
});

Answer №3

One simple way to accomplish this task is by utilizing map, reduce, or a for..of loop.

1) Using map

const initialArray = [
  { name: "john", age: 12, height: 178, likes: "music" },
  { name: "mike", age: 22, height: 181, likes: "sport" },
  { name: "anna", age: 18, height: 175, likes: "sleep" },
  { name: "paul", age: 24, height: 170, likes: "drink" },
];

const result = initialArray.map(({ name, height }) => ({ name, height }));
console.log(result);

2) Using reduce

const initialArray = [
  { name: "john", age: 12, height: 178, likes: "music" },
  { name: "mike", age: 22, height: 181, likes: "sport" },
  { name: "anna", age: 18, height: 175, likes: "sleep" },
  { name: "paul", age: 24, height: 170, likes: "drink" },
];

const result = initialArray.reduce((acc, { name, height }) => {
  acc.push({ name, height });
  return acc;
}, []);
console.log(result);

3) Using for..of loop

const initialArray = [
  { name: "john", age: 12, height: 178, likes: "music" },
  { name: "mike", age: 22, height: 181, likes: "sport" },
  { name: "anna", age: 18, height: 175, likes: "sleep" },
  { name: "paul", age: 24, height: 170, likes: "drink" },
];

const result = [];
for (let { name, height } of initialArray) {
  result.push({ name, height });
}
console.log(result);

Answer №4

One alternative approach is to use lodash's pick function (in case you require the ability to dynamically determine the property names) or you can also utilize ramda's pick methods which accomplish the same task.

const result = initialArray.map(R.pick(['name', 'height']));

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

Learning Angular2: What is the mechanism behind the automatic incrementation of the ID variable in this particular section?

In This specific part of the Angular2 Tutorial there is a feature that allows users to add new items to an array. Somehow, when the item is added, the ID is automatically incremented but the exact process behind this automation remains a mystery. I am awa ...

The $.post method is malfunctioning

I am experiencing an issue where the onchange function is working properly, but the $.post function is not functioning as expected. Below is the HTML code snippet: <input type="checkbox" id="chk" value="3" onchange="checkradio(this.value)"/> Here ...

I am a newcomer to Stack Overflow and I am facing difficulty in getting my form to submit successfully

Excuse any errors as I am new to this. I am facing an issue where my form is not submitting anything in the console. Could it be because my entire HTML file is within a return statement from a JavaScript function? I assumed it would work since I imported a ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Ensuring session data is updated when saving a mongoose model

I am facing a challenge with updating express session data in the mongoose save callback. Is there a way to access and modify the session data from within line 4 of the code? app.get('/', function(req, res){ var newModel = new Model(somedata); ...

Error in jQuery: Null property causing TypeError when reading 'text'

Issue: I have a modal form that is loaded via an ajax call. Inside the modal, there is a span element containing an email address. I am trying to capture the value of this span element using JavaScript. Currently, I have a button click event that triggers ...

The Datatable feature is malfunctioning, unable to function properly with Javascript and JQuery

As a novice in the world of jquery/javascript, I find myself struggling with what may seem like an obvious issue. Despite following tutorials closely (the code for the problematic section can be found at jsfiddle.net/wqbd6qeL), I am unable to get it to wor ...

When $(.class) displays result, Javascript ceases execution

In the code snippet below, I am trying to load a group of products from a category when the user clicks on the .expandproducts button: $('.expandproducts').click(function(){ id = $(this).attr("data-id"); urlajax = document.location.origi ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...

Enhance your website's accessibility by using JavaScript to allow the down and up arrow keys to function

Thank you for taking the time to read this, any feedback is greatly appreciated. The current script on my website is only partially functional (click "i" in the bottom right corner). Currently, the script will focus on the first link AFTER pressing the T ...

What is the best way to disregard all pathNames and display my index.php file directly from the root of my website?

After a user clicks on a navigation link on my website, the page is loaded into a content window within the same page using JavaScript. I then utilize HTML 5 to modify the URL and create a history entry, resulting in a URL resembling the one mentioned (). ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

The masonry reorganization is behaving strangely

I've recently started using masonry for the first time and you can check it out here: Although I have managed to set it up, I am facing some issues with its positioning of boxes when dragging items in. For example, instead of placing a medium-sized ...

Tips for resolving the error message: React is not able to identify the `currentSlide` and `slideCount` prop on a DOM element

I recently implemented an image slider using "react-slick" in my next.js project. However, I encountered some warnings in the console related to the 'currentSlide' and 'slideCount' props on a DOM element. Warning: React does not recogni ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...

Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on Everyth ...

Display a particular div when a specific image is present within another div

I'm currently working on a task, but I'm having trouble with it. If I have an image called smiley.png within a div with the class "selected." <div class="selected" style=""><img width="25" height="24" src="images/smileys/smiley.png ...

Expecting a declaration statement for exporting React

When attempting to export my component, I encounter an error in my editor stating export declaration statement expected Here is the code snippet: export Header from './Header/Header'; However, if I modify it like this: export {default as Head ...