Shorten a value within an array of objects using JavaScript

How can I truncate a value in an array of objects based on specific criteria?

Let's use the following example:

var items = [
{
  name: "CN=arun, hjsdhjashdj,jsdhjsa,kshd",
  status: "Present"
}, {
  name: "CN=manohar, abcdefghij,111111,2222222",
  status: "Present"
}, {
  name: "manohar",
  status: "Absent"
}]

I want to truncate the value only if it contains "CN=" and update the array accordingly.

The desired updated array should be:

var items = [
{
  name: "CN=arun...",
  status: "Present"
}, {
  name: "CN=manohar...",
  status: "Present"
}, {
  name: "manohar",
  status: "Absent"
}]

To achieve this, I need to check for the presence of "CN=" in each string, truncate at the first comma, add "..." and then update the same array using forEach method.

Answer №1

If you want to shorten a string by truncating it after the first occurrence of CN= and adding ellipses, you can loop through the items, look for CN=, split at the first comma, then append ...

items.forEach(item => {
    if (item.name.includes("CN=")) {
        item.name = item.name.split(",")[0] + "...";
    }
});

Answer №2

You have the option to replace any unwanted sections.

function modify(o) {
    o.name = o.name.replace(/,.*$/, '...');
}

var list = [{ name: "CN=arun, hjsdhjashdj,jsdhjsa,kshd", status: "Present" }, { name: "CN=manohar, abcdefghij,111111,2222222", status: "Present" }, { name: "manohar", status: "Absent" }];

list.forEach(modify);

console.log(list);

Answer №3

Utilize String manipulation techniques.

var items = [
{
  name: "CN=arun, hjsdhjashdj,jsdhjsa,kshd",
  status: "Present"
}, {
  name: "CN=manohar, abcdefghij,111111,2222222",
  status: "Present"
}, {
  name: "manohar",
  status: "Absent"
}];
items.forEach(function(item){
  if(item.name.includes('CN=')){
    var values = item.name.split(',');
    item.name = values[0] + '...';
  }
});

console.log(items);

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

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

After a successful login, learn how to implement a bottom tab menu in React Native

I'm diving into the world of react-native and finding myself a bit lost when it comes to routing and navigation. I have 4 screens - Login, Register, Home, and Links. The Register and Login screens are all set up, with the ability to navigate back usin ...

Tips for saving JSON information into a variable using JavaScript

I am in need of a function called ** getJson () ** that can fetch and return data from a json file. Here is the JSON data (file.json): [ { "01/01/2021":"Confraternização Universal", "1 ...

The website code lacks a dynamically generated <div> element

When using jQuery to dynamically add content to a "div" element, the content is visible in the DOM but not in the view page source. For example: <div id="pdf"></div> $("#btn").click(function(){ $("#pdf").html("ffff"); }); How can I ensur ...

Different types of outputs that are suitable for a callback

I am currently developing a small node.js project focused on retrieving search terms from a Twitter feed. Although the search functionality is in place, I am facing difficulties in displaying this data on my webpage. The information I wish to showcase is s ...

Master the art of fetching response data from an API and implementing a function to process the data and generate desired outputs using Node.js and JavaScript

Being new to node.js, javascript, and vue, I attempted to create a Currency Converter by fetching data from an API for exchange rates and performing calculations in a function. Despite successfully obtaining the exchange rates from the selected country in ...

"Optimize Magellan Sidebar for Mobile Devices by Relocating it to the Bottom of the Page

After spending a week working with Foundation 5 framework, I'm curious if there is a straightforward way to make my magellan sidebar shift to the bottom of the page when viewed on mobile or tablets. <div data-magellan-expedition="fixed"> <di ...

Tips for Customizing Dialogs with CSS Classes in mui5 Using Emotion/Styled

When attempting to customize the styling of a mui Dialog, I encountered an issue where it wouldn't accept className even when placed inside PaperProps. While inline styles worked, my preference was to import styles from a separate stylesheet named Sty ...

Tips for formatting input boxes on the client side

Q: How can I format my textbox so that when a user enters a number, such as one, it will be displayed as 0000001? The goal is to have any number entered be shown in 7-digit format. ...

The property 'push' cannot be read because it is undefined

$scope.AddTask = function () { $scope.tasks.push([{ "taskName": $scope.taskName, "priority": $scope.selectedP }]); }; $scope.tasks = [{ "taskId": 1, "taskName": "task 1", "priority": 1 }, { "taskId": 2, "taskName ...

Observing changes in a parent component variable with Angular

One feature of my form is that it consists of a parent component and a child component. To disable a button within the form, I utilize a function called isDatasetFilesValid() which checks a specific variable (datasetList[i].fileValid). This variable is mo ...

Determine whether two elements in an array are the same. Print "yes" if they are, and "no" if they are not, for each comparison

Is there a way to verify if two elements in an array are equal and display "Yes" if they are, or "No" if the new string has not been inserted into the array before? The challenge I am facing is that even though I insert 6 elements into the array, I want ...

Exploring Frontend Package Dependencies in Different Versions

As I develop the React frontend for a library package, I want to clearly display to users the specific version of the library being utilized. Apart from manual methods or relying on Node.js, I am unsure of alternative approaches to achieve this. I am curi ...

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

What is the best way to keep the textfield value at 0? If you clear the textfield, it will result in another value being

If I don't input anything in this field, the total will show as isNaN, and I want to prevent form submission if it is isNaN. How can I stop the form from being submitted when the total value is isNaN? export default function BasicTextFields() { cons ...

Ways to retrieve a specific field from an array of objects stored in a text document

Struggling to extract solely the refresh_token field from a text file using file_get_contents. Any assistance would be greatly appreciated. {"access_token":"XXXX","token_type":"bearer","expires_in":3600,"refresh_token":"XXXX"} ...

When generating a fresh event and attempting to link the event ID to its creator, unexpected obstacles emerged

I am currently working on an application that revolves around events. One of the key features requires users to be logged in to create events, and upon creation, I need to update the user's events array with the event ID. However, I have encountered a ...

A straightforward redirection in Express involving a static file

Just starting out with Node and Express and encountering a bit of trouble. I have a static html page where users enter their username via ajax to my server, and then I want to redirect them to another html file. const express = require("express"); const b ...

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...