Select specific columns from an array using Typescript

I have a collection of objects and I'm looking for a way to empower the user to choose which attributes they want to import into the database. Is there a method to map and generate a separate array containing only the selected properties for insertion?

For instance, let's consider the following object array:

[
    {name: 'name1', address: 'addr1', phone: '123'},
    {name: 'name2', address: 'addr1', phone: '123'},
    {name: 'name3', address: 'addr1', phone: '123'},
    {name: 'name4', address: 'addr1', phone: '123'},
]

If the user chooses name and phone, the resulting array to be inserted in the database should appear as follows:

[
        {name: 'name1', phone: '123'},
        {name: 'name2', phone: '123'},
        {name: 'name3', phone: '123'},
        {name: 'name4', phone: '123'},
    ]

Is there a way to achieve this efficiently?

Answer №1

Utilize the map method to create a new object

const arr = [
    {name: 'name1', address: 'addr1', phone: '123'},
    {name: 'name2', address: 'addr1', phone: '123'},
    {name: 'name3', address: 'addr1', phone: '123'},
    {name: 'name4', address: 'addr1', phone: '123'},
];

const res = arr.map(({name, phone}) => ({name, phone}));
console.log(res);

If you wish to make it more flexible with an array of properties to duplicate

const arr = [
    {name: 'name1', address: 'addr1', phone: '123'},
    {name: 'name2', address: 'addr1', phone: '123'},
    {name: 'name3', address: 'addr1', phone: '123'},
    {name: 'name4', address: 'addr1', phone: '123'},
];

const copy = ['name', 'phone'];

const res = arr.map(data => copy.reduce((o, k) => (o[k] = data[k], o), {}));

console.log(res);

Answer №2

Use the array.map method to transform an array of objects.

let people = [
    {name: 'John', age: 30, city: 'New York'},
    {name: 'Alice', age: 25, city: 'Los Angeles'},
    {name: 'Bob', age: 35, city: 'Chicago'},
]

let transformedPeople = people.map((person) => {
  return {
    name: person.name,
    age: person.age
  }
});

console.log(transformedPeople)

Answer №3

If you ever find yourself needing to work with specific column values such as ['name', 'phone'], you can utilize a handy helper function known as pick that allows you to create objects containing only a subset of properties:

function pickKeys(keys, data) {
    const result = {};
    for (const key of keys) {
        if (key in data) {
            result[key] = data[key];
        }
    }
    return result;
}

With this implementation, simply provide an array of keys along with the source object, and pickKeys will generate a new object containing only the specified keys:

const obj = { name: 'John', address: '123 Main St', phone: '555-1234' };

console.log(
    pickKeys(['name', 'phone'], obj)
);

//////////////////////////////////////////////////

function pickKeys(keys, data) { const result = {}; for (const key of keys) { if (key in data) { result[key] = data[key]; } } return result; }

To extend this functionality to an array of objects, you can combine Array.map with pickKeys like so:

const dataArr = [
    {name: 'Alice', address: '456 Elm St', phone: '555-5678'},
    {name: 'Bob', address: '789 Oak St', phone: '555-9012'}
];

console.log(
    dataArr.map((item) => pickKeys(['name', 'phone'], item))
);

//////////////////////////////////////////////////

function pickKeys(keys, data) { const result = {}; for (const key of keys) { if (key in data) { result[key] = data[key]; } } return 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

Combining the power of Google Blockly with AngularJS

I am looking for a way to empower advanced users to create and save custom math formulas that will be used in a shopping cart check-out process. These users are not programmers, but can follow instructions easily. The formulas should be editable by the use ...

Unable to download tsc through the Terminal on OS X

Struggling to install tsc, encountering numerous errors upon running it. Reinstalled node and npm multiple times, adjusted npm flag to verbose, here's the output: Mitch:~ mitch$ npm install -g typescript npm info it worked if it ends with ok ... Fe ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

The issue at hand involves Javascript, Ajax, latte, and Presenter where there seems to be a restriction on using GET requests for a file located

I have a query. I’ve been given the task of adding a new function to our web application. It was built on PHP by someone else, so it's proving quite challenging for me to debug as I am not familiar with this technology. I’m attempting to incorpor ...

Is there a way to collapse child elements in a hover sidebar using Vuetify?

My project includes a sidebar that opens when I hover over it with the mouse. Everything works fine, but within the sidebar, there is a collapse dropdown menu. When I open this menu and then move the mouse away from the sidebar and back again, the collapse ...

Please enter a numerical value into the input field in a JavaScript form

<script> function loop() { var input = document.getElementById('inputId').value; for (var i = 0; i < input; i++) { var result = document.getElementById('outputDiv').innerHTML ...

Guide to sending post variables in an AngularJS service

Is there a way to send POST variables to a RESTful API using an angularjs service? I currently have the following setup: angularjsServices.factory('LoginService', [ '$resource', function($resource){ return function(user, pass){ ...

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...

Selecting Laravel lists by month option

I'm encountering a problem here. The error message reads "Too few arguments to function App\Http\Controllers\ViewsController::OBviews(), 0 passed and exactly 1 expected" Here is my controller: public function OBviews($date) { ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...

Exploring Angular2: A Guide to Interpolating Expressions in Templates

Is it possible to interpolate different types of Javascript expressions? Along with displayed properties like object.property and short expressions such as {{1+1}}, what other valid Javascript expressions can be used for interpolation? ...

How can I execute JavaScript code within Aptana Studio 3 IDE?

After creating a Test.js file, I added two lines of JavaScript code: var x = 5; console.log("The answer is: " + x); The desired output would be: "The answer is: 5" I am curious if there's a way to view this outcome in the Aptana Scripting console, ...

Transform the date format from Google Forms to TypeScript

I am currently facing an issue with a Google Form connected to a Google Spreadsheet. The date format in the spreadsheet appears as follows when a response is received: 20/02/2023 18:58:59 I am seeking guidance on how to convert this date format using Type ...

Ways to create a clickable anchor tag without using any text

I am currently designing my own website and incorporating links to various social media platforms using icons. However, I am facing an issue where the links are not clickable. For a detailed look at my problem, you can refer to this JSFiddle: http://jsfid ...

How can I implement the vm. syntax using ControllerAs in my application?

After reading various sources, including a few discussions on Stack Overflow, I have come to understand that the ControllerAs syntax is gaining popularity as it aligns with how things are done in Angular 2. Therefore, I decided to delve deeper into unders ...

Utilizing VueJs @error handler for managing broken image links

I am encountering a strange issue with the VueJS @error handler. My goal is to hide images with broken links and display a placeholder instead. However, when I have two images with broken links, only the first image displays the placeholder while the other ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...

The Element type does no feature a Typescript property

Despite my attempts to include a declaration file and various other solutions, I'm still struggling with this issue: The goal is to define the visible property as a function on the HTML Element object. However, the linter keeps flagging visible with ...

Ways to determine the total number of npm packages installed, excluding development dependencies

Is there a specific NPM command I can run from the CLI to count only the installed NPM Modules in my package that are not Dev Dependencies? When I use npm ls, it lists all packages without distinguishing between regular dependencies and DevDependencies. ...

Tips on avoiding redirection when submitting a form

Upon making an AJAX call to a page, I receive a form with user parameters. This form is later submitted to a URL in order to create a session for the same user in advance. When that person visits the site, they should see their name displayed. To achieve ...