Reputation: 1038
i'm trying to fix and get expected result but am failed.
let sample obj=
[{ profile: admin, availableAction: 'You have [Access: write][Option: print] only few options'},
{ profile: cust, availableAction: 'You have [Access: write][Option: print] only few options'}
]
i want to print only 'You have only few options'
to achive this, i tried below possible way but failed
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log('KEY---->', key + ' -> ' + obj[key]);
if (obj.includes('[Access: write][Option: print] ')) {
obj = obj.replace(/\[(.*)\]/, '');
}
}
}
but getting cannot read property error.
could some one tell me how to fix this properly.
Note: I know its duplicate thread, i tried as much as possible solution from SO. but couldn't make use of it effectively.
Thanks in advance
Upvotes: 0
Views: 2686
Reputation: 7665
You can take advantage of a replacer function that can be passed to JSON.stringify
. After stringification you can parse the JSON string back to an object using JSON.parse
let obj = [
{ profile: "admin", availableAction: 'You have [Access: write][Option: print] only few options'},
{ profile: "cust", availableAction: 'You have [Access: write][Option: print] only few options'}
];
const result = JSON.parse(JSON.stringify(obj, (k, v) =>
(k === "availableAction")
? v.replace('[Access: write][Option: print] ', '')
: v
));
console.log(result)
Upvotes: 1