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

I am having trouble grasping certain syntax in JavaScript when it comes to using `${method_name}`

I'm having trouble understanding some of the syntax in this code, particularly ${method_name}. I'm not sure what we are achieving by passing the method name within curly braces. global._jsname.prototype.createEELayer = function (ftRule) { if ...

Stretching the Mantine Accordion Section

The Mantine accordion requires that its content be of type Accordion.Item, as indicated in the documentation for the children props. This means that even functions returning AccordionItem will not be recognized. Therefore, only AccordionItem(s) created in ...

Design a background image that is optimized for both high-resolution retina displays and standard non-ret

Scenario I am working on a web page where I want the background image to be fixed, covering the entire screen or window (excluding tablets and smartphones). The background image has been created using ImageShack. Everything is running smoothly so far. T ...

Ways to reset input fields following form submission

I've been trying to figure out how to clear the input fields once the form is submitted, but for some reason, the input data remains there even after each submission. I'm using ajax jquery form. Any ideas on how to resolve this issue? Thank you ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Is there a way to verify if all elements within an array are identical?

For example, please confirm $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; but not this: $a[0]=1; $a[0]=2; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; Thank you :) ...

Updating values in an array if they exceed a certain threshold

I'm facing a little issue with a straightforward concept. I have an array of data and would like to substitute each value if it exceeds a certain threshold, let's call it X. To tackle this problem, I devised a small script to illustrate the solu ...

Tips for calculating the distance from the cursor position to the visible area

Is there a way to determine the cursor's offset from the top of a textarea's view rather than its position? While e.target.selectionStart provides the cursor position, $el.scrollTop gives the scroll offset of the textarea. Any suggestions on ho ...

Having trouble adding a div in React due to the error "Objects are not allowed as a React child"?

While I am rendering the data and displaying it between divs, I keep getting this error: Objects are not valid as a React child (found: Wed Dec 09 1998 00:00:00 GMT+0530 (India Standard Time)). If you meant to render a collection of children, use an ...

Tips on storing a blob (AJAX response) in a JSON file on your server, not on the user's computer

After researching extensively on creating a URL from or downloading a blob in a computer, I require a unique solution: (1) Save a blob in own server into a JSON file, (2) Optimize the way to update a database using the data stored in the JSON. My attemp ...

Why is my jQuery SlideReveal not displaying on page load?

Can anyone provide some help? I am currently using the jquery.slidereveal.js plugin from ''. The plugin works well when manually clicking the trigger to open and close the menu. However, I would like it to default to its last state on page load, ...

Can you explain the significance of the declaration "char (* ( *f())[])();"?

While researching pointers to functions, I stumbled upon this intriguing declaration: char (* ( *f())[])(); I attempted to decipher the meaning behind it, but unfortunately came up empty handed... Can anyone shed some light on what this refers to? ...

Utilizing JSON Data with JQuery: A Beginner's Guide

I am using a setTimeout function to reload another function every 5 seconds. The update_list function is responsible for rendering entrances in a view. However, when there are many entrances and you have scrolled down, the list empties and reloads every e ...

Integrating VueJs into a pre-existing .net core 5 project

I am currently working on a .net core solution that consists of 9 different projects including api, dto, data, service, etc. I now have the requirement to incorporate a project that utilizes the Vue.js framework for the frontend within this existing .net ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Incorporating Javascript jQuery functionalities from an external file

I have encountered an issue when trying to run my index.html file with the control.js file that I outsourced. It seems like they are not working together properly: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.c ...

Detecting Changes in Angular2 Component Attributes via Observables

When working with Angular 2 components that have input attributes defined using @Input, how can I create an observable to track changes to those input attributes (not to be confused with user input from a form)? export class ExampleComponent implement OnC ...

The issue I am facing is with the post_logout_redirect_uri not functioning properly when using localStorage in an OIDC Auth

authority: 'yyy', client_id: this.'yyy', redirect_uri: 'http://localhost:4200/login', response_type: 'token', scope: 'yyy', post_logout_redirect_uri: & ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

During the execution of a function, the React list remains empty which leads to the issue of having

Having difficulty preventing duplicate values because the item list is always empty when the function is called, even though I know it contains items. The function in question is AddToCart, being passed down to a child component named inventoryModal. The ...