Home > Back-end >  javascript get string text from json data
javascript get string text from json data

Time:03-19

I'm creating a table in react using material UI and trying to figure out how to extract itemlocation from itemInfo and store it in a new column in the table. I know I can do it from the back end, but I can't, and all I want is to be able to extract the string from the item info. I provided an example of how the table and I'll put should look, as well as a snippet of sample code, and I hope this helps because this is how I was thinking of doing it, and I was hoping if anyone knew how I could do it without going into the backend.

simple code

[{
      field: "itemInfo",
      headerName: "itemInfo",
      headeralign: "center",
      align: "left",
      width: "136",
      type: "string",
      editable: true,
    },
{
      field: "itemlocation",
      headerName: " itemlocation",
      headeralign: "center",
      align: "left",
      width: "136",
      type: "string",
      editable: true,
      renderCell: (params) => {
        return (
          <> </>
        );
      }
    },]

Json data

[{
            "id": "2433-10",
            "busiName": "ABC",
            "srTypeId": "2433-10",
            "nodeType": "0",
            "pathName": "home",
            "busiSort": 10,
            "itemInfo": "1:sql test question:  itemlocation=USA",
            "superTypeId": "002",}]

Original MUI Table

itemid itemname itemInfo
12 car 1:sql test question: itemlocation=USA
99 toy 1:sql test question: itemlocation=USA

I want extract just itemlocation from itemInfo into New table columns

itemid itemname itemInfo itemlocation
12 car 1:sql test question: itemlocation=USA USA
99 toy 1:sql test question: itemlocation=USA CHAIN

CodePudding user response:

let newFormat = items.map(item => {
    return {
        newProperty: item.oldProperty
    }
});

CodePudding user response:

If you already have access to itemInfo you could run a method similiar to below

const extractLocation = (itemInfo) => {
    return itemInfo.match(/itemlocation=(.*)/)[1]
}

This uses regular expression matching to find just the text after itemlocation. If you expect other text that isnt the location to be added to your itemInfo string later on you can update it to exclude that text.

To call this method(assuming your json data is an array of object) you could do.

const location = extractLocation(json[0]['iteminfo'])

// or for all locations

const locations = json.map((item) => {
 return extractLocation(item['itemInfo'])
}
  • Related