Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables

data =
{
   SCHOOL-ADMISSION_YEAR: "2021"
   SCHOOL-SCHOOL_NAME: "ABC SCHOOL"
   SCHOOL-SCHOOL_LOCATION: "NEWYORK"
   ENROLLMENT-ADMISSION_YEAR: "2021"
   ENROLLMENT-SUBMISSION_DATE: "2020-04-02"
   ENROLLMENT-ENROLLMENT_DATE: "2020-06-02"
}

The desired groups are

 School =
  {
   ADMISSION_YEAR: "2021",
   SCHOOL_NAME: "ABC SCHOOL",
   SCHOOL_LOCATION: "NEWYORK",
  }

 Enrollment =
  {
   ADMISSION_YEAR: "2021",
   SUBMISSION_DATE: "2020-04-02",
   ENROLLMENT_DATE: "2020-06-02",
  }

var school = data.filter(p => p.contains('SCHOOL'));
var enrollment = data.filter(p => p.contains('ENROLLMENT'));

Answer №1

When working with plain objects that don't have a built-in filter method, you must iterate through them using a loop. One way to filter and map an object is by first converting it to an entry array and then back again using ES2019's fromEntries:

const school = Object.fromEntries(
  Object.entries(data)
  .filter(([key]) => key.includes('SCHOOL-'))
  .map(([key, val]) => [key.replace('SCHOOL-', ''), val])
);

For an array of objects, the process is slightly different:

const school = Object.entries(data)
  .filter(([key]) => key.includes('SCHOOL-'))
  .map(([key, val]) => ({ [key.replace('SCHOOL-', '')]: val }));

Answer №2

Here's a solution that should meet your needs:

function findItemsWithSubstring(substring) {
  let itemsWithSubstring = [];

  for (let key of Object.keys(items)) {
    if (key.includes(substring)) {
      itemsWithSubstring.push(items[key])
    }
  }
  return itemsWithSubstring;
}

You can then use it like this:

findItemsWithSubstring("BOOK"); // => ['The Book Thief', 'Book Club', 'Bookstore']
findItemsWithSubstring("FILM"); // => ['Film Festival', 'Action Films', 'Foreign Films']

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

Unlocking location data in React Router-DOM 6: A step-by-step guide

I am currently working on implementing a 'forgot password' feature, where I am attempting to transfer the email data from the 'login page' to the 'forgot password' page using a Link element. However, I am encountering an issu ...

The Gateway to Github: Unveiling the Mysteries through a

I need assistance in creating a static web page that can extract and showcase all the latest pull requests from a specified GitHub repository. My intention is to utilize octokit.js, but it seems to be designed for node.js. Is there any simple approach to ...

Confused about the concept of an SWR subscription

As I navigate through SWR's various features, there is one that has caught my attention: SWR-subscription. The concept of "subscribing to real-time data sources with SWR" is unfamiliar to me and I am seeking an explanation along with a straightforward ...

How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in r ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with: function toggleTable(){ document.getElementById ...

What is the best way to apply "display: none;" on a span element nested within a title attribute?

I am utilizing the social-share-button gem to share blog posts on social media. The website has been internationalized, making it bilingual (English and German). Everything is functioning correctly, but I encounter an issue with the social share buttons wh ...

Exploring the concept of reflection in JavaScript and jQuery

Here is a javascript object I have: person.Name = "John"; person.Nick = "Smith"; person.Info = "hi there"; In addition, I have some HTML elements as shown below: <input id="Name" /> <input id="Nick" /> <input id="Info" /> My question ...

Error in Jest Testing: An unexpected character '@' was encountered

Encountering issues with NuxtJS Jest tests and attempting to build a Nuxt app to test URL's due to route name errors in some components. Here is the code snippet I tried: beforeAll(async () => { nuxt = new Nuxt({ ...config, server: { port: 3001 } ...

How can we use jQuery to extract an HTML element's external stylesheet and add it to its "style" attribute?

My goal is to extract all CSS references from an external stylesheet, such as <link rel="stylesheet" href="css/General.css">, and add them to the existing styling of each HTML element on my page (converting all CSS to inline). The reason for this re ...

What is the best way to upload a file to Firebase Storage using React?

I am facing difficulty uploading a file to Firebase in order to retrieve its getDownloadURL. This is the code snippet I currently have: import React, {useState, useEffect} from 'react' import { Container, Button, Row, Col, Form, Alert } from &ap ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = Objec ...

Tips for using JavaScript to set images from Flickr API as img src

I've been attempting to populate a table with images fetched from flickr. The array I'm using consists of urls like: ["https://www.flickr.com/photos/113081696@N07/24695273486", "https://www.flickr.com/photos/113081696@N07/24565358002", "https:// ...

Having trouble grasping the inner workings of code while iterating through a JSON array in ReactJS

Currently, I am immersed in a school project that requires me to develop a simple CRUD web application. After weighing my options, I decided to utilize Spring Boot + ReactJS for this endeavor. The progress has been smooth so far, but I must admit that part ...

Ensure that this specific attribute remains responsive by either setting it within the data option or initializing it for class-based components. Vuex is another viable option to consider for managing state

Terminal Error in vue.runtime.esm.js:4573 [Vue warn]: The property or method "setRegisterEmail" is not defined in the instance but referenced during rendering. Please ensure that this property is reactive, either in the data option, o ...

Steps to retrieve an ext.js grid using data from a database

I've been struggling to make a basic Ext.js application work, which is supposed to pull data from a database and show it in an Ext.js grid. However, all I keep getting is "Failure:true". If you could help me identify the mistake, that would be great. ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

The error message for ExpressJS states: "Headers cannot be set after they have already been sent."

Currently, I'm facing a challenge with ExpressJS and am having trouble finding the necessary documentation to resolve it. Technology Stack: body-parser: 1.17.0 express 4.15.0 multer: 1.3.0 MongoDB Postman The current view consists of 3 fields: n ...

Issues arise when JQuery functions fail to execute

This unique program showcases a series of error messages that are designed to appear under specific conditions. These conditions are identified through PHP code, following which the essential JQuery script is echoed via PHP to display the messages. Initia ...

What are the steps for installing the latest version of popper, v2?

When you run the following command: npm install popper.js --save You will receive a warning message that says: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f1eef1f1e4f3afebf2c1b0afb0b7afb0">[email& ...