Home > Blockchain >  Best way to slice a string that is stored in an object
Best way to slice a string that is stored in an object

Time:12-20

I am trying to slice a string that is stored in an object, but I am getting an error because I believe you cant use .slice() on values stored in an object.

paidData.id contains the id of the invoice and is a string, which I have confirmed with typeof

function paidCard(paidData) {

    // Converting epoch seconds to human readable date
    const invoiceDue = moment.unix(data.due_date);
    const invoiceDueConverted = invoiceDue.format(' MMMM Do YYYY');

    // Executing the function to convert amout due.
    const amountDue = decimalInsert(data.amount_due);
      const test = paidData.id; // <--- Logged this to console and it exists
      const result = test.slice(5) // <--- Cant read properties of undefined error here
  
    
    // Shows a notification when data from database has been loaded
    return(
      <InvoiceCard
      paid={true}
      invoiceStatusIconContainerColor='rgba(2,49,7,0.7)'
      invoiceStatusIconColor='#29DA7A'
      invoiceStatusText={paidData.status}
      customerName={paidData.customer_name}
      invoiceId={paidData.id}
      invoiceIdTextColor='#5C5C5C'
      customerEmail={paidData.customer_email}
      customerAddress={paidData.customer_address}
      invoiceAmount={amountDue}
      invoiceDateIconStatusColor='#FA3C3C'
      invoiceDateText={invoiceDueConverted}
    />
    );
  };
  let invoiceData = []
  let paidInvoiceData = []
  
  // Render the invoices by mapping through state.
  if(data && paidData && Array.isArray(data) && Array.isArray(paidData)) {
     invoiceData = data.map(card);
     paidInvoiceData =  paidData.map(paidCard);

Error I am getting

TypeError: Cannot read properties of undefined (reading 'slice')

CodePudding user response:

It doesn't matter where the string is located (in an array, in an object, or in a variable). You can slice it normally:

var object = {id: '12345'};
console.log(object.id.slice(0,3)); // returns 123

CodePudding user response:

You can call the .slice() method on any string, even if it is stored in an object. For example, this would be valid JS code:

const obj = { str: "StackOverflow is good" }
console.log(str.slice(0,12)) // "StackOverflow"

However, .slice() does not mutate the string it was called on. JS does not provide a .splice() (mutating) for strings, so you'll have to polyfill it. Check out this question for a good polyfill.

  • Related