In JavaScript, sort the array of objects based on the key name

I have an array of objects like the following:

 employees = [
    {name: "Tony Stark", department: "IT"},

    {name: "Peter Parker", department: "Pizza Delivery"},

    {name: "Bruce Wayne", department: "IT"},

    {name: "Clark Kent", department: "Editing"}
];

I am looking to filter the array of objects to display only the names:

 employees = [
    {name: "Tony Stark"},

    {name: "Peter Parker"},

    {name: "Bruce Wayne"},

    {name: "Clark Kent"}
];

Answer №1

A useful method to employ in this scenario is map()

const employees = [
  { name: "Tony Stark", department: "IT" },
  { name: "Peter Parker", department: "Pizza Delivery" },
  { name: "Bruce Wayne", department: "IT" },
  { name: "Clark Kent", department: "Editing" }
];

const result = employees.map(({ name }) => ({ name }));

console.log(result);

const employees = [
  { name: "Tony Stark", department: "IT" },
  { name: "Peter Parker", department: "Pizza Delivery" },
  { name: "Bruce Wayne", department: "IT" },
  { name: "Clark Kent", department: "Editing" }
];

const result = employees.map((employee) => { 
  return { 
    name: employee.name 
  }
});

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

What could be causing filterOptions to behave unexpectedly in React?

Why is the list filter not working as expected when using the Material Autocomplete component? Here is my code: Link to Code import * as React from "react"; import Typography from "@mui/material/Typography"; import TextField from &quo ...

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

utilizing javascript function in Icefaces applications

I'm facing an issue. Here's the situation: I'm working on a quiz game where I need to implement a timer using JavaScript (jquery.timer.js). I have created a JavaScript file (question.js) with a method called startTimer, which utilizes the jq ...

Preventing conflicts while toggling visibility with JQuery across various groups

My navigation system allows me to show/hide divs and toggle an 'active' class on the navigation items. However, I've encountered conflicts when trying to use similar sections on the same page (clicking a link in one section affects divs in o ...

Using ajax.actionlink to display the desired text

When using an ajax.actionlink @Ajax.ActionLink("Add Last Name", // <-- Text to display "AddTimeSeriesData", // <-- Action Method Name etc.... @id = "link") How can I extract the link text in JavaScript? I attempted to use $(&apo ...

A guide to locating a dynamic JSON array using the JSON Path Finder tool in Node.js

I am looking to extract some dynamic IDs from a JSON file using the JSON path finder in an npm package. Sample.json [ { "4787843417861749370": [ { "type": "Fast delivery", ...

You may encounter issues with invoking methods on a JavaScript object in Node.js after using res.send for response sending

Exploring Context and Design Overview Currently, I am utilizing a library known as Tiff.js to seamlessly load Tiff images on a designated webpage. The usage of this library extends both to the server-side and client-side functionalities. On the server end ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

"A problem with PrimeNG where the model value does not get updated for the p-auto

<p-autoComplete [style]="{'width':'100%'}" name="searchSuggestions" [(ngModel)]="suggestion" (completeMethod)="searchSuggestions($event)" [suggestions]="searchSuggestionsResult" field="field"></p-autoComplete> Utilizing t ...

{"Error":"The chosen action cannot be processed with the HTTP method 'PUT'."}

(I am able to use GET and DELETE methods successfully, but I am encountering an issue with the PUT method. Why is it not working? The error message displayed is: {"Message":"The requested resource does not support http method 'PUT'."} empObj = ...

The type 'Observable<HttpEvent<DeviceList>>' cannot be assigned to the type 'Observable<DeviceList>'

// FUNCTION TO RETRIEVE DEVICE LIST fetchDeviceList(): Observable < DeviceList > { this.setToken(); return this.http.get<DeviceList>(this.api_url + '/devices', this.httpOptions1) .retry(2); } I am facing a challenge in this p ...

The web server is serving an HTML file instead of the expected JSON response

Is there a way to extract the JSON data from ? I have tried using AJAX but it only retrieves the entire HTML page instead. $.ajax({ url: 'http://www.bartdekimpe.be/anoire/index.php/admin/getGamesUserJson/34', success: function(data) { ...

Improving code quality and consistency in Javascript: Tips for writing better code

Hey, I've been experimenting with some code using ajax and have ended up with a lot of repetitive lines. Is there a way to streamline the code without losing functionality? I keep using the .done method multiple times when I could probably just use it ...

Is there a way to navigate to the adjacent values in a json array?

I've been struggling with this issue for quite some time now. I have a list of items that can be moved to a div when clicked. My goal is to navigate through the items in the list (json) by clicking on Next and Previous buttons. As someone who is rela ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

Exploring the power of a mapped type within a tuple

Can TypeScript ensure the validity of key-value tuples in this function? function arrayToObject(array, mapper) { const result = {}; for(const item of array) { const [key, value] = mapper(item); result[key] = value; } return ...

What steps do I need to take in order to ensure that this angular8 component occupies the entire height

Is there a way to make this angular8 component fill the entire height of the screen? https://i.sstatic.net/JIupj.png In the Root Style.scss file, the following code is present: html, body, app-root { min-height: 100vh; height: auto; margin: 0; } ...

Manipulate and scale with jQuery

I am currently utilizing the jQueryUI library with its Draggable and Resizable functionalities to resize and drag a div element. However, I am encountering some unexpected behavior where the div jumps outside of its container upon resizing. How can I resol ...

Guide to logging data from a response using the console

I have a function that retrieves data from an API: return this._http.get(`api/data`) .map((response: Response) => response.json()); What is the best way to debug or inspect the response, besides using console.log(response.json())? ...