"Is there a JavaScript code snippet that can retrieve information from a JSON file

Is there a way to create a custom JavaScript function that can extract specific data from a JSON object based on certain keywords? I am working with a Task Manager API and would like to automatically populate fields based on the task title. Here is an example of the JSON data:

{
 "data": {
    "boards": [
      {
        "owner": {
          "id": 555555555
        },
        "groups": [
          {
            "id": "new_group",
            "title": "Forecasts",
            "items": [
              {
                "id": "355670938",
                "name": "PIPE: Production & Client Management | STAGE: New Support Intake | NAME: TESTY | DATE: 10/27/2019 | TIME: 8:00 am | TIME ZONE: Central Time | DURATION: 60 minutes | TYPE: All Virtual | AUDIENCE VIEW:"
              }
            ]
          }
        ]
      }
    ]
  },
  "account_id": 55555555
}

I specifically want to retrieve the information for DATE, TIME, DURATION, and TYPE from items.name. How can I create a function to extract only this data?

Answer №1

To begin, you must first pinpoint the exact location from which you wish to extract the information.

Next, simply separate the content using pipes, followed by colons.

let targetStr = getTree().data.boards[0].groups[0].items[0].name;
let fields = ['DATE', 'TIME', 'DURATION', 'TYPE'];

console.log(extractData(targetStr, fields));

function extractData(str, fields) {
  return str.split(/\s*\|\s*/).reduce((res, entry) => {
    let dat = entry.split(/\s*:\s*/);
    return fields.indexOf(dat[0]) > -1 ? Object.assign(res, { [dat[0]]: dat[1] }) : res;
  }, {});
}

function getTree() {
  return {
    "data": {
      "boards": [{
        "owner": {
          "id": 555555555
        },
        "groups": [{
          "id": "new_group",
          "title": "Forecasts",
          "items": [{
            "id": "355670938",
            "name": "PIPE: Production & Client Management | STAGE: New Support Intake | NAME: TESTY | DATE: 10/27/2019 | TIME: 8:00 am | TIME ZONE: Central Time | DURATION: 60 minutes | TYPE: All Virtual | AUDIENCE VIEW:"
          }]
        }]
      }]
    },
    "account_id": 55555555
  };
}
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}

Answer №2

One possible solution is to split the items' names using a pipe character without ever using it in the data. Then, you can filter out only the elements that start with "DATE:", "TIME:", "DURATION:", or "TYPE:".

items.name.split('|').filter(data => /^(DATE:|TIME:|DURATION:|TYPE:)/.test(data));

Answer №3

JSON.parse() is a method that can be used to convert a JSON string into a JavaScript object. Once you have the JavaScript object, you can easily access and return the value of any specific key within it.

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

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

import the JSONP file from the local directory and assign it to a variable on

My current setup involves a local webpage that is loading a large JSON database file by utilizing a file named data.jsonp that contains data={a JSON dictionary of information}. I then import this file in my HTML using <script src="data.jsonp"& ...

Tips for executing a script on the "body" using "body onload=myfunc()" in an ASP.NET content page

I have included my script "myscript.js" in the master page. Now, in a content page, I want to load myscript() on startup (body onload). Is there a way to accomplish this? ...

Operating Node SerialPort on a CentOS 6 Linux environment

Hi everyone, I'm a beginner in node.js and I've recently developed an application using node, express, socket, and serialport. I have a weighing scale connected to serialport (COM2) which works perfectly on my Windows localhost. However, when I t ...

Quoted strings within a CSV input are transformed into doubly-escaped characters

I am currently working on utilizing JQ for processing a CSV file that does not contain any column headings: cat "input.csv" "12345678901234567890","2019-03-19",12 Is there a more elegant and easily readable method to eliminate escaped quotes from the fir ...

JavaScript Autocomplete Validation

I'm working on a web page that has two TextBoxFor fields with Javascript autocomplete. The first field, ClientUser, receives a response that includes both an integer and a string. I need to compare this integer with another integer field on the page, ...

React Hook for modifying a value within an array of objects in real-time

Is there a way to update the score of each player with a simple click? I have already implemented the initial code and all that's left is to define the function that will trigger the score update for each user. The increment value is +1. const [p ...

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

What is the meaning of this CSS acronym?

div[id^=picture]:target{ /*applying various styles here*/ } I stumbled upon the snippet of code shown above on a website discussing CSS image galleries. Can anyone clarify what this code accomplishes? Appreciate it. ...

What steps can I take to ensure my CSS component remains unaffected by the global CSS styles?

My navbar component is not displaying the styles correctly as intended. I have a Navbar.module.css file to style it, but after using next-auth for social login, only the buttons remain unstyled while everything else gets styled. The code snippet for impor ...

Exploring the differences between server-side rendering and client-side rendering in Express using Pug

I find myself in a state of confusion when it comes to distinguishing between what is considered client-side and server-side. Currently, as I develop a website using Pug for my HTML pages without any external files being loaded into the client's brows ...

The computed value failing to refresh

I'm facing an interesting issue. I am currently developing a simple time tracking application. Here is the form I have created: <form class="form" @submit.prevent="saveHours"> <div class="status"> <div class="selector" v-f ...

Utilizing an Express API within a Kubernetes environment to enhance functionality for React and React Native

Currently, I am in the process of learning Kubernetes and have set up an Apollo-express GraphQL API along with a React frontend and a React Native app. I am trying to figure out how to connect my GraphQL API with both the frontend and mobile apps - what se ...

"Kindly complete all mandatory fields" - The undisclosed field is preventing me from submitting

I am facing an issue with my WordPress page that has Buddyboss installed along with Elementor pro as the Pagebuilder. The Buddyboss plugin provides Facebook-like functions on the website. While it is easy to comment on posts within the Buddy Boss system, I ...

Using the setTimeout function with asynchronous tasks

I have a situation where I need to introduce a 5000ms delay before firing an asynchronous function. To accomplish this, I attempted to utilize the setTimeout() method. This async function is called within a loop that runs multiple times, and each time it i ...

Tips for managing asynchronous code that invokes other asynchronous code in AngularJs

My factory utilizes indexedDB and a method called getRecipe that relies on this indexed db to fetch data. The issue arises because indexedDB returns its instance in an asynchronous call, and getRecipe is another method that also returns its value asynchro ...

What is the most effective method for exchanging variables between programs or threads?

I currently have a program that executes an algorithm processing real-time data. Once per hour, the algorithm's parameters are optimized based on new historical data. Currently, this optimization process is running in a single thread, pausing the rea ...

Using Jersey to successfully bind JSON data to intricate Java classes

As I develop my RESTful API with Jersey, the use of JSON is essential. I am aware that Jersey relies on Jackson for automatically binding JSON to Java classes. However, I find myself a bit confused about the dependencies involved in this process. It appear ...

Choosing an array from the MongoDB database

{ "_id": "4f609932615a935c18r000000", "participants": [ { "user_name": "john1", "role": "user", "created_at": { "sec": 1331730738, "usec": 810000 }, { "user_name": "john2", "role": ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...