john smith
john smith

Reputation: 21

Splitting string into array then using one of the values to be displayed in JavaScript

I have the code below which is in JSX format. r.invoice_details gives me an output that looks like this

{"rate":1522,"quantity":1,"discount":null,"itemName":"Gold Members club (offline)","amount":1522,"noEdit":true}

It's in a form of string. All I want is itemName inside the string to be displayed. What's the best way to write as an inline function?

{
  id: "itemName",
  label: "Item",
  customCell: (r, i) => {
    return <td key={`${i}-itemName`}>
      {r.invoice_details}
      </td>;
  }
},

Upvotes: 1

Views: 78

Answers (3)

COLLINSba4
COLLINSba4

Reputation: 1

Try Object.values after extractiong JSON.parse()

  let json = JSON.parse(r.invoice_details)
   let inv =   Object.keys(json)
   let inv2 = Object.values(json)
   let Id = inv2[inv1.indexOf("itemName")]

Upvotes: 0

Abheeth Kotelawala
Abheeth Kotelawala

Reputation: 142

You can use JSON.parse()

const json = '{"rate":1522,"quantity":1,"discount":null,"itemName":"Gold Members club (offline)","amount":1522,"noEdit":true}';
const obj = JSON.parse(json);

console.log(obj.itemName);

So your end code will look something like this,

{
  id: "itemName",
  label: "Item",
  customCell: (r, i) => {
    return <td key={`${i}-itemName`}>
      {JSON.parse(r.invoice_details).itemName}
      </td>;
  }
},

Upvotes: 1

GabrielMC
GabrielMC

Reputation: 288

You can use the JSON.parse() function:

{JSON.parse(r.invoice_details).itemName}

So your final code will look like this:

{
  id: "itemName",
  label: "Item",
  customCell: (r, i) => {
    return <td key={`${i}-itemName`}>
      {JSON.parse(r.invoice_details).itemName}
      </td>;
  }
},

Upvotes: 0

Related Questions