Home > Blockchain >  How to replace all occurrences inside an object?
How to replace all occurrences inside an object?

Time:10-26

I have an object like this:

users = [{
  "userid": "1",
  "fornonmods": "<div id=\"user1\" data-login=\"\" data-status=\"online\" class=\"item\">",
  "formods": "<div id=\"user1\" data-login=\"\" data-status=\"online\" class=\"item\">"
}, {
  "userid": "19917",
  "fornonmods": "<div id=\"user19917\" data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\" class=\"item\">",
  "formods": "<div id=\"user19917\" data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\" class=\"item\">"
}];

I want to replace all the occurrences of
data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\"
with
data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"gagged\"
just like I would do with replace() but the thing is that that only works with strings and I am not allowed to convert this object into a string.
What can I do in this cases?

CodePudding user response:

You need to iterate over users and replace with regex pattern.

const searchString = new RegExp('data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\"', 'g');
const replacement = 'data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"gagged\"';
const parsedUsers = users.map(x=>{
  return {
    userid: x.userid,
    fornonmods: x.fornonmods.replace(searchString,replacement),
    formods: x.formods.replace(searchString,replacement)
 }
})

CodePudding user response:

map is what you're looking for

const users = [{
  "userid": "1",
  "fornonmods": "<div id=\"user1\" data-login=\"\" data-status=\"online\" class=\"item\">",
  "formods": "<div id=\"user1\" data-login=\"\" data-status=\"online\" class=\"item\">"
}, {
  "userid": "19917",
  "fornonmods": "<div id=\"user19917\" data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\" class=\"item\">",
  "formods": "<div id=\"user19917\" data-login=\"kBr4pelyDy4yKVmiAAAD\" data-status=\"online\" class=\"item\">"
}];

const id = "kBr4pelyDy4yKVmiAAAD";

const res = users.map(x => {
   const container = {};

   container.userid = x.userid,
   container.fornonmods = x.fornonmods.replace(`data-login=\"${id}\" data-status=\"online\"`, `data-login=\"${id}\" data-status=\"gagged\"`);
   container.formods = x.formods.replace(`data-login=\"${id}\" data-status=\"online\"`, `data-login=\"${id}\" data-status=\"gagged\"`);

   return container;
});

console.log(res);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

  • Related