What is the best way to extract specific properties from a list of Objects and convert them into a JSON format?

My list currently consists of objects with the following structure:

[ Person({ getName: Function, id: '310394', age: 30 }), Person({ getName: Function, id: '244454', age: 31 })...]

Now, I am looking to transform it into this format:

{
    peopleIds: [
         244454,244454...
  ]
}

I attempted the following method:

public makePeopleIdJSON(list: Person[]):void {
    list.forEach(x => console.log(x.id))
  }

This code only logs the id for each object in the list. How can I convert this output into a JSON in the requested format?

Thank you very much.

Answer №1

Check out this code snippet:

interface Employee{
    empId: number;
}
function generateEmployeeIDs(array: Employee[]) {
    return {
        employeeIDs: array.map(item => item.empId)
    }
}

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

Navigating nested JSON structures using the aeson library

My task is to parse JSON data in a specific format using the aeson library. {"field":{"name":"..."}} or {"tag":{"name":"..."}} or {"line":{"number":"..."}} The goal is to create a customized data type as follows: data Rule = Line Integer | ...

Add jQuery and underscore libraries to an AngularJS component

For my new service, I am incorporating angularjs, underscore, and jQuery: myModule.factory('MyService', ['MyResource', function (MyResource) { .... // Utilizing _ and $ }]); How can I properly inject underscore and jQuery int ...

Interactive JavaScript navigation featuring dynamic menu options using AJAX and JSON data

Here is the HTML code that I have written: <!-- JavaScript DropDown Menu --> <label>Select the group</label> <select id="group" onchange="yyyyy";> <option value="">Select the group</option> </select> <script ...

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...

The process of altering a span label's class with JavaScript

I am currently working with an HTML element that looks like this: <dd><span class="label label-success" id="status">Production</span></dd> My goal is to update it to: <dd><span class="label label-warning" id="status"> ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

How to incorporate paginating in MongoDB operations

It's a well-known fact that using skip for pagination can lead to performance issues, especially as the data set grows larger. One workaround is to leverage natural ordering using the _id field: //Page 1 db.users.find().limit(pageSize); //Get the id ...

Why does the value of my input get erased when I add a new child element?

I seem to be facing an issue when I try to add an element inside a div. All the values from my inputs, including selected options, get cleared. Here's a visual representation of the problem: https://i.sstatic.net/UpuPV.gif When I click the "Add Key" ...

The database is not being updated with the new values

Is it possible to retrieve data from a database and modify it using AJAX? I tried changing the input, but AJAX keeps sending the original data stored in the database. <script> function showMore(str) { var xhttp; if (str.length == ...

Posting data to an HTML file with a foreign key matching the input value in Express.js

My discussion platform features topics and comments. Each comment has its own unique topic_id. Currently, I am able to post comments for the initial topic, but encountering issues when adding new comments for other topics. I am looking for guidance on effi ...

The rating script fails to update when multiple ratings are applied simultaneously

Greetings! I am currently in the process of developing a rating script and encountering some issues. At the moment, the script is somewhat functional -> The problem arises when I open two browsers, load image 1 on both, and rate the image in each brow ...

Merge looping array in PHP using CodeIgniter

After retrieving two arrays from separate database queries, I aim to merge them in a specific way outlined below The following code executes the first query: $query = $this->db->query("SELECT kec,pilihan,COUNT(pilihan) as total FROM votes GROUP BY ...

Guide to transferring token specifications to a different webpage using Angular 2

I have successfully implemented JWT login in my Angular2 application. After logging in, I want to display the first and last name of the user on the profile page. However, being new to Angular, I am seeking guidance on how to achieve this. Below is my cod ...

Ways to ensure that a function operates independently for each cloned div and not the original

I'm facing an issue where a jquery function needs to be executed when the drop-down is changed. However, the problem arises when I clone the div element and make changes in the drop-down of the newly cloned element, the effect takes place in the first ...

Is there a way to send data to a sibling component without the need to store it as a variable?

In my project, I am utilizing bootstrap vue cards within a v-for loop. Within this loop, one of the tags is supposed to return a value based on the current iteration of v-for. My challenge is that when I save this value as a variable and pass it to another ...

The presence of fs.existsSync as a function is not recognized when importing electron

I am currently developing a Vue and Electron application and I encountered a problem while trying to restart the application. Here is my code snippet: import { app } from 'electron'; export default { name: 'Home', methods: { re ...

After installing the latest version of [email protected], I encountered an error stating "Module 'webpack/lib/node/NodeTemplatePlugin' cannot be found."

Upon updating to nextjs version 10.1.3, I encountered an error when running yarn dev. Error - ./public/static/style.scss Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin' Require stack: - /path_to/node_modules/mini-css-extract-plugi ...

How can I implement disabling buttons for specific IDs in React?

I'm currently developing an interactive quiz application with React that features multiple choice questions. I've implemented state management to track and increment the user's score when they select the correct answer option, but there&apos ...

The error "Init map is not a function" occurs when the Google Maps API is activated after the page is published on WordPress, but does not appear when the page is in

Utilizing the Google Maps API to generate a map where users can outline the perimeter. An error only appears when the page is live. It appears that the page attempts to load the map before receiving it from the API, resulting in an error. I've attemp ...

Issue with Bootstrap collapsible menu not expanding when clicked

I want to make my collapsed navbar menu expand when clicked on a small screen. I've customized a Bootstrap navbar to split my links at each end of the bar. Right now, the links collapse when the screen size decreases, but clicking on the accordion but ...