'javascript get string text from json data
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
const columns1 = [{
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
const Rows =[{
"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 |
Solution 1:[1]
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'])
}
Solution 2:[2]
let newFormat = items.map(item => {
return {
newProperty: item.oldProperty
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Scott |
| Solution 2 | stackers |
