What is the best way to extract a specific substring from an object's property in JavaScript?

I am facing an issue with extracting and displaying only the year from the date property of objects in an array. The current script I have displays all the years for each object instead of tying it to the individual object.

Here is the code snippet:

//array of objects
objArray = [
  {
    foo: 1,
    bar: "December 5, 2020"
  },
  {
    foo: 3,
    bar: "April 2, 2019"
  },
  {
    foo: 5,
    bar: "January 6, 2018"
  }
];

//get year from date
let result = objArray.map((a) => a.bar.substr(-4));

//template literal
function objArrayTemplate(obj) {
  return `
    <p>Item ${obj.foo}</p>
    <p>Year: ${result}</p>
    <p>***********</p>
  `;
}

//output
document.getElementById("objArrayResult").innerHTML = `${objArray
  .map(objArrayTemplate)
  .join(" ")}`;
<div id="objArrayResult"></div>

Answer №1

Retrieve only the year from the data stored in the objArrayTemplate method.

//array of objects
objArray = [
  {
    foo: 1,
    bar: "December 5, 2020"
  },
  {
    foo: 3,
    bar: "April 2, 2019"
  },
  {
    foo: 5,
    bar: "January 6, 2018"
  }
];

//create a template using a literal string
function objArrayTemplate(obj) {
  return `
    <p>Item ${obj.foo}</p>
    <p>Year: ${obj.bar.substr(-4)}</p>
    <p>***********</p>
  `;
}

//display the output on the webpage
document.getElementById("objArrayResult").innerHTML = `${objArray
  .map(objArrayTemplate)
  .join(" ")}`;
<div id="objArrayResult"></div>

Answer №2

To retrieve the timestamp, utilize the new Date() method and extract the full year from it.

Check out the functional code snippet below:

<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>
<body>
    <div id="objArrayResult"></div>
    <script>
        //array of objects
        objArray = [
            {
                foo: 1,
                bar: new Date(),
            },
            {
                foo: 3,
                bar: new Date(),
            },
            {
                foo: 5,
                bar: new Date(),
            },
        ];

        // template literal
        function objArrayTemplate(obj) {
            return `
                <p>Item ${obj.foo}</p>
                <p>Year: ${obj.bar.getFullYear()}</p>
                <p>***********</p>
            `;
        }

        // output;
        document.getElementById("objArrayResult").innerHTML = `${objArray
            .map(objArrayTemplate)
            .join(" ")}`;
    </script>
 </body>
</html>

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

Rails - removing list item upon deletion of parent object

Currently working on a project app as part of a full stack developer bootcamp program. One of the features I'm implementing is a destroy method to remove an item from a list. Using AJAX requests, the goal is to dynamically remove the li element repres ...

Exploring an array of NSObjects that contain nested arrays

I am working with an Array containing PhRecords. To simplify things, let's assume the object structure is as shown below: @interface PhRecord : NSObject @property (nonatomic, strong) NSArray *PhName; //Person's name @property (nonatomic, strong ...

Modifying HTML line codes using Python: A step-by-step guide

If only I could modify this particular line: <button _ngcontent-c19="" class="blue-button-disabled" disabled="">CONTINUE </button> to be like this instead: <button _ngcontent-c19="" class="blue- ...

Can you give a varied reply without storing any information?

Is there a way to simulate a server endpoint so that each time a user accesses the API, extra properties are added to the response? For example, initially the endpoint returns: [{id: 1, price:null}] Then, with each subsequent call, it adds new informati ...

The interface cannot be assigned to the type of Record<string, unknown>

I recently created a generic react component that looks like this: export interface GenericTableProps<T extends Record<string, unknown>> { columns: Column<T>[]; data: T[]; } const GenericTable = <T extends Record<string, unknow ...

In order to comply with JSX syntax rules in Gatsby.js, it is necessary to enclose adjacent elements

I want to apologize beforehand for the code quality. Every time I attempt to insert my HTML code into the Gatsby.js project on the index.js page, I encounter this error: ERROR in ./src/components/section3.js Module build failed (from ./node_modules/gatsb ...

Create a Java program that randomly generates an integer and keeps track of how many times it occurs

I'm currently working on a program that calculates how many times a user can flip a coin, with up to 1000 flips allowed. The program generates a random integer between 1 and 10 (even numbers represent heads, odd numbers represent tails) and stores all ...

Is it feasible to completely erase the coding history of a website that has been indexed

Is it possible to completely erase the code-history of a website once it has been indexed by Google and other search engines? I have some content on a website that I want to remove from history, but I'm not sure if it's possible due to factors li ...

Increasing the range of numbers with Jquery's span functionality

Recently, I've been experimenting with jQuery in my WordPress theme project. I wanted to spice things up a bit by adding some cool features. After receiving some helpful JS code from a great website, I used it to wrap numbers in a specific div with a ...

Routes are no longer being qualified by Express once a subdomain is incorporated

We had developed a compact app that was working flawlessly, but then we were tasked with transforming it into something accessible for others in our organization to utilize... and that led to everything breaking down. Our initial setup included a simple ex ...

I've exhausted all my knowledge but still unable to get Tailwind to work

I've been troubleshooting Tailwind for the past 6 hours. Managed to set it up in a simpler Nextjs/React/Typescript project, but struggling to get it working in this larger codebase. I'm sure I'm missing something obvious, but I'm at a ...

What is the best way to generate a hierarchical bar graph using d3.js?

I was attempting to modify Mike Bostock's Sortable Bar Chart by removing the transition property and sorting the bars based on their length, similar to how it is displayed in this example, without any interactivity. <!DOCTYPE html> <meta cha ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Add a button feature to both upload and download a todo list within a JavaScript file, similar to a text file

I'm looking to enhance my simple todo list with a download and upload function. I want to be able to save the list in local storage and then upload or download it from a server code. Below is a link to my code: https://jsfiddle.net/zahrashokri/uqkn6t ...

Selection dropdown not being populated by ng-options

After trying numerous examples to implement the changes, I am still facing issues. Even though I have an ng-model and clearly defined the object property I want to receive, it is not functioning as expected. Any assistance would be appreciated. Here is th ...

Easiest method for creating an array literal within MySQL

Is there a more efficient way to retrieve the array [1,2,3] in MySQL without having to create a table using CTE and then grouping it? I attempted to achieve this using the following query: SELECT '1', [1,2,3] MySQL '8.0.20' Error Co ...

Interactive drop-down menu, utilizing $_GET method to handle spaces in input

I have successfully implemented a dynamic drop-down menu using JavaScript/jQuery and populated it with PHP MySQL: $("#first-choice").change(function() { $("#second-choice").load("getter.php?choice=" + $(this).val()); }); Everything is working as ...

Guide on using Twitter Typeahead.js to capture all matching elements in a specific string

When using twitter typeahead.js, it typically returns elements that match only at the beginning of a string. For example: source: ['type','typeahead','ahead'] query: 'type' Returns: 'type' and 'type ...

Guide to Importing a Dictionary to a UIPickerView

Is it possible to load data from a dictionary into a PickerView in Swift? I have a dictionary with String keys representing States and Double values representing taxes. My goal is to use the keys as titles in the UIPickerView and display the selected key& ...

Is there a way to detect duplicate usernames in a form without actually submitting the form, and then automatically focus on the username field if a duplicate is

I need help with a user registration form that I am creating. I want the form to automatically search for an existing username as soon as the user starts typing in the username field. If the username already exists, I want the field to receive focus. In my ...