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

Steps to retrieve the central coordinates of the displayed region on Google Maps with the Google Maps JavaScript API v3

Is there a way to retrieve the coordinates for the center of the current area being viewed on Google Maps using JavaScript and the Google Maps JavaScript API v3? Any help would be greatly appreciated. Thank you! ...

Implementing fetch within a custom hook to display a loader within a return function

customFetch hook: import React, { useState, useEffect } from 'react'; const customFetch = (url, options) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); useEffect(() => { (async () ...

Tips for triggering a keyboard event to the parent in Vue 3

In my Vue 3 project, I have components nested five levels deep. The top-level component named TopCom and the bottom-level component called MostInnerCom both contain a @keydown event handler. If MostInnerCom is in focus and a key is pressed that it cannot ...

Ways to Personalize Navbar in the Bulma Framework

How can I make the <router link> element in my navbar component full width? I'm also looking for keywords related to achieving this layout. Here is an image of the issue: https://i.sstatic.net/2f2b0BcM.png I want a layout that spans the full ...

Widget for navigating through Youtube videos

I am currently working on creating a widget that allows users to navigate a YouTube video using buttons. For instance, if the video is of a car race, there would be buttons labeled Lap 1, Lap 2, and so forth. My idea involves adding an extension to the vi ...

Having trouble setting up an input tag to successfully submit the form and trigger the opening of a BootStrap Modal

Is there a way for me to submit a form to my servlet and open a BootStrap Modal simultaneously using an input tag in my .jsp file? I've tried setting the input tag type to "button" but then I can't submit the form. And when I set it to "submit", ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...

Monitoring and refining console.error and console.log output in CloudWatch

I've encountered a situation where my lambda function includes both console.error and console.log statements, which Node.js interprets as stderr and stdout outputs respectively. However, upon viewing the logs in CloudWatch, I noticed that they appear ...

Utilizing web components from NPM packages in conjunction with Svelte

My current project involves the development of a simple Single Page App (SPA) using Svelte. I have successfully implemented a basic layout and styling, as well as an asynchronous web request triggered by a button click. Now, my next objective is to utiliz ...

Are multiple instances of ajax being executed within the modal?

Currently, I am working on a feature that requires an Ajax request. To begin with, the process involves opening a modal by clicking a button with the class '.open-email-modal'. Within this modal, there are two input fields to enter registration d ...

Setting up CSS module class names in a Vue project using Vite js configuration

Within my vite.config.ts file, I have specified a configuration for CSS modules. return defineConfig({ ... css: { ... modules: { localsConvention: "camelCase", generateScopedName: "[name]__[local]__[hash:base64:2]" ...

The JSON property is not defined

After making an AJAX call to retrieve data, I receive a JSON Object instead of a string. When I log the object, all its properties appear correctly. However, when attempting to log one specific property, it shows up as undefined. Here is a snapshot of my ...

tips for invoking a method on a petite-vue/VueJS component

I have a small Vue Petite component with the following template. When the button is clicked outside, I want to trigger the clear() method on the component to let it clear itself. <template id="input-template"> <input type=&q ...

Guide for Vue.js Bootstrap Table: Retrieving and Storing Row IDs in a Data Property

I'm working with a Vue.js Bootstrap table and I need to store each table row id in either an Array or Object data property. Below is a sample bootstrap table template: <template v-slot:cell(label)="row" > <div > ...

Implementing Node.js on several domains with the help of express.vhosts()

I'm facing a challenge with my nodejs setup. I am in the process of developing a node server that will support multiple instances of app.js running simultaneously on the same system using express.vhost(). However, I seem to have hit a roadblock. The ...

Can a JavaScript string be converted into a date format for insertion into a SQL database?

I'm currently developing a bot and facing an issue where I need to make it upload two dates. However, the arguments it can have are numbers within strings. For example, I have two strings '08222020' and '10282022,' which I need to ...

How can I assign a value other than a string to a placeholder or vue property?

As I develop a content management system using Nuxt and Pug/Jade, I am looking for an efficient way to create a list of input fields for users to enter information. My idea is to use the v-for directive to render the list and dynamically set the value and ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

Implementing multiple filters with jQuery

Make a Selection `<select class="form-control" id="technology"> <option name="sort" value="2g" id="2g"gt;2G</option> <option name="sort" value="3g" id="3g"&g ...

Set the local storage value to the $scope variable

I am attempting to set a local storage value to a $scope variable and utilize that $scope variable in ng-model to populate dropdowns. However, the code I have tried is not functioning as expected. You can view the Plunker example here: https://plnkr.co/ed ...