Retrieve particular attributes from an array of objects

I have an array of JavaScript objects structured as follows:

  let users = [{
    "id": 9,
    "name": "Sulaymon",
    "family": "Yahyaei",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deadabb2bfa7b3b1b0b6b99ebbaab2b9acf0bdb1b3">[email protected]</a>",
    "tel": "(91) 247-52-15",
    "isActive": 0,
    "level": "User",
    "email_verified_at": null,
    "created_at": "2019-10-30 04:56:18",
    "updated_at": "2019-10-30 04:56:18"
}, {
    "id": 8,
    "name": "Rasul",
    "family": "Irmatov",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77251604021b3712031b10055914181a">[email protected]</a>",
    "tel": "(91) 524-57-96",
    "isActive": 0,
    "level": "User",
    "email_verified_at": null,
    "created_at": "2019-10-24 12:28:45",
    "updated_at": "2019-10-24 12:28:45"
}]

I want to extract an array of objects from my Column object :

let columns = [
  {label: 'Name', name: 'name', show: true},
  {label: 'Family', name: 'family', show: true},
  {label: 'Email', name: 'email', show: true},
  {label: 'Telephone', name: 'tel', show: true},
  {label: 'Level', name: 'level', show: true},
  {label: 'Date Added', name: 'created_at', show: false},
  {label: 'Email Verification', name: 'email_verified_at',show: false},
  {label: 'Updated At', name: 'updated_at', show: false},
  {label: 'Status', name: 'isActive', show: false},
];

If the show property is set to true, then include it in the result, which should look like this :

let userData = [{
    "name": "Sulaymon",
    "family": "Yahyaei",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2754524b465e4a48494f406742534b40550944484a">[email protected]</a>",
    "tel": "(91) 247-52-15",
    "level": "User"
}, {
    "name": "Rasul",
    "family": "Irmatov",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="491b283a3c25092c3d252e3b672a2624">[email protected]</a>",
    "tel": "(91) 524-57-96",
    "level": "User"
}]

What steps should I take next?

Answer №1

let clients = [{
    "id": 9,
    "name": "Sulaymon",
    "family": "Yahyaei",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2655534a475f4b49484e416643524a41540845494b">[email protected]</a>",
    "tel": "(91) 247-52-15",
    "isActive": 0,
    "level": "Client",
    "email_verified_at": null,
    "created_at": "2019-10-30 04:56:18",
    "updated_at": "2019-10-30 04:56:18"
}, {
    "id": 8,
    "name": "Rasul",
    "family": "Irmatov",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c597a4b6b0a985a0b1a9a2b7eba6aaa8">[email protected]</a>",
    "tel": "(91) 524-57-96",
    "isActive": 0,
    "level": "Client",
    "email_verified_at": null,
    "created_at": "2019-10-24 12:28:45",
    "updated_at": "2019-10-24 12:28:45"
}]

let headers = [
  {label: 'Full Name', name: 'name', show: true},
  {label: 'Last Name', name: 'family', show: true},
  {label: 'Personal Email', name: 'email', show: true},
  {label: 'Contact Number', name: 'tel', show: true},
  {label: 'Client Level', name: 'level', show: true},
  {label: 'Date Joined', name: 'created_at', show: false},
  {label: 'Email Verified?', name: 'email_verified_at',show: false},
  {label: 'Last Updated', name: 'updated_at', show: false},
  {label: 'Account Status', name: 'isActive', show: false},
];

let clientData = [];

clients.forEach(client => {
  var obj = {};
  
  headers.forEach(header => {
    if (header.show) {
      obj[header.name] = client[header.name]
    }
  });
  clientData.push(obj);
});

console.log(clientData);

Answer №2

If you want to achieve the desired outcome, consider utilizing the map and filter functions in your code

let users = [{"id": 9,"name": "Sulaymon","family": "Yahyaei","email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34474158554d595b5a5c537451405853461a575b59">[email protected]</a>","tel": "(91) 247-52-15","isActive": 0,"level": "User","email_verified_at": null,"created_at": "2019-10-30 04:56:18","updated_at": "2019-10-30 04:56:18"}, {"id": 8,"name": "Rasul","family": "Irmatov","email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c89aa9bbbda488adbca4afbae6aba7a5">[email protected]</a>","tel": "(91) 524-57-96","isActive": 0,"level": "User","email_verified_at": null,"created_at": "2019-10-24 12:28:45","updated_at": "2019-10-24 12:28:45"}]
  , columnsToShow = [{label: 'Name', name: 'name', show: true},{label: 'Family', name: 'family', show: true},{label: 'Email', name: 'email', show: true},{label: 'Telephone', name: 'tel', show: true},{label: 'Level', name: 'level', show: true},{label: 'Date Added', name: 'created_at', show: false},{label: 'Email Verification', name: 'email_verified_at',show: false},{label: 'Updated At', name: 'updated_at', show: false},{label: 'Status', name: 'isActive', show: false},
                    ].filter(d => d.show).map(d => d.name)

let result = users.map(d => Object.assign(...columnsToShow.map(c => ({ [c]: d[c] }))))

console.log(result)

Answer №3

let people = [{
    "id": 9,
    "name": "Sulaymon",
    "family": "Yahyaei",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4979188859d898b8a8c83a48190888396ca878b89">[email protected]</a>",
    "tel": "(91) 247-52-15",
    "isActive": 0,
    "level": "User",
    "email_verified_at": null,
    "created_at": "2019-10-30 04:56:18",
    "updated_at": "2019-10-30 04:56:18"
    },
    {
    "id": 8,
    "name": "Rasul",
    "family": "Irmatov",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e7c4f5d5b426e4b5a42495c004d4143">[email protected]</a>",
    "tel": "(91) 524-57-96",
    "isActive": 0,
    "level": "User",
    "email_verified_at": null,
    "created_at": "2019-10-24 12:28:45",
    "updated_at": "2019-10-24 12:28:45"
    }];
let attributes = [
  {label: 'Name', name: 'name', show: true},
  {label: 'Family', name: 'family', show: true},
  {label: 'Email', name: 'email', show: true},
  {label: 'Telephone', name: 'tel', show: true},
  {label: 'Level', name: 'level', show: true},
  {label: 'Date Added', name: 'created_at', show: false},
  {label: 'Email Verification', name: 'email_verified_at',show: false},
  {label: 'Updated At', name: 'updated_at', show: false},
  {label: 'Status', name: 'isActive', show: false},
];

people.map((person) => {
return attributes.filter(attribute => attribute.show).reduce((acc, attribute) => {
acc[attribute.name] = person[attribute.name];
return acc;
}, {});
})

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

Is it possible to obtain Ionic components without relying on Angular?

I am looking to develop an application using Ionic and VueJS. I am interested in incorporating Ionic components into Vanilla JavaScript - is there a library or resource available for this? ...

React Native vector icons display enigmatic symbols

I recently installed react-native-vector, but I'm seeing strange symbols when using it. Can anyone provide guidance on how to properly utilize this library? Platform: Android import React from 'react'; import {View, Text, StyleSheet} from & ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

What is the best way to implement a user-customizable dynamic URL that incorporates API-generated content in a NextJS and React application?

Seeking assistance with implementing customizable dynamic URLs in Next.js with React. My current project involves a Next.js+React application that uses a custom server.js for routing and handling 'static' dynamic URLs. The goal now is to transiti ...

What is the best way to retrieve the nearest or preceding object regardless of the document's layout using jQuery?

Here are some examples to illustrate the concept: <ul> <li id="o1" class="elem">apple</li> <li id="o2" class="elem">banana</li> <li id="o3" class="elem">orange</li> </ul> **$('#o2').exact ...

Retrieve the identifiers of various HTML elements and store them in an array

Within a div, there are multiple objects. I am trying to retrieve the IDs of all elements based on their class, knowing that the number of elements may vary. So far, my attempt has been: arr = $(".listitem #checkBox").hasClass('checkedItem').att ...

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

React - Although the array in the state is being updated, only the first object in the array is visible on the screen

I'm currently working on developing a web application using the PokeAPI. My primary objective is to retrieve and display a variety of Pokemon based on their type. At the moment, I've set my API URL to specifically fetch fire type Pokemon. Howeve ...

What are the best ways to engage with a div element using keyboard shortcuts?

Is it possible to enable keyboard shortcuts for interacting with div elements? I am working on a project tailored for seniors who may have difficulty using a mouse. Is there a way to utilize keyboard shortcuts to click on divs and access their contents? H ...

Encountering issues with browser tabs and Socket.IO

I'm currently working on a real-time chat using Socket.IO, but I've encountered a major issue. The aim is to allow users to log in, select another connected user, and start chatting... var http = require('http'), fs = require(&ap ...

What causes variations in the output of getClientRects() for identical code snippets?

Here is the code snippet provided. If you click on "Run code snippet" button, you will see the output: 1 - p.getClientRects().length 2 - span.getClientRects().length However, if you expand the snippet first and then run it, you will notice a slight dif ...

Comparing nestableSortable with the Nestable JavaScript library

I am in the process of developing a navigation menu editor that consists of multiple nested, sortable forms. My goal is to submit all the form data in one comprehensive JSON data blob. After researching, I have narrowed down my options to two libraries: n ...

JavaScript library for making HTTP requests

Can someone provide guidance on creating a JavaScript command line application that interacts with a public API using an HTTP client library? What is the preferred JavaScript HTTP library for this task? ...

Issue with AngularJS ngGrid rendering incorrect page size and malfunctioning pagination

I'm currently working on implementing ngGrid data pagination for some data retrieved from a service. The table displays correctly and the search filter is functional. However, despite setting the pageSize in my pagingOptions to 25, the table shows all ...

How can I stop v-dialog from closing automatically?

Utilizing the <v-dialog> component in my web app to display a form, I am facing the challenge of implementing an unsaved changes dialog that pops up when a user attempts to close the form without saving. The dilemma lies in preventing the default clo ...

Invoke a class method once the Promise has been successfully resolved

I'm facing an issue with my simple class class A{ constructor(){ this.loadComponents().then(function(values) {callbackOnLoad();}); } callbackOnLoad(){ //do some things } loadComponents(){ ... return Promise.all([p1,p2,p3,p4,p ...

Converting a JavaScript string containing an `import` statement into a browser-compatible function

Can my vue application transform the given string into a callable function? const test = 'import { pi } from "MathPie"; function test() { console.log(pi); } export default test;' The desired output format is: import { pi } from "M ...

Node.js TypeError: Unable to access property 'path' of an undefined object

In my Nodejs implementation, I am working on uploading various types of files (photos, mp3, pdf) to Amazon Web Services S3. Right now, I am focusing on uploading an mp3 file but keep encountering the error: "TypeError: Cannot read property 'path' ...

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 ...