Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Replacing all string values in an object that match a pattern?

I'm looking for an efficient way to replace the values within an object if they match a certain pattern.

var shapes = {
  square: {
    attr: {
      stroke: '###',
      'stroke-width': '%%%'
    }
  },
  circle: {
    attr: {
      fill: '###',
      'stroke-width': '%%%'
    }
  }
}

For instance, i'd like to be able to replace all '###' patterns with a colour for a specific shape:

var square = replace(shapes.square, {
  '###': '#333',
  '%%%': 23
});

var circle = replace(shapes.circle, {
  '###': '#111',
  '%%%': 5
});

Which would allow me quickly to set the stroke and/or fill values of various objects.

Is there a way to do this cleanly? Perhaps using Lodash or regex?

like image 584
Scotty Avatar asked Feb 28 '26 08:02

Scotty


2 Answers

Plain JS, no library needed:

var shapes = {
  square: {
    attr: {
      stroke: '###',
      'stroke-width': '%%%'
    }
  },
  circle: {
    attr: {
      fill: '###',
      'stroke-width': '%%%'
    }
  }
}
shapes = JSON.parse(
  JSON.stringify(shapes).replace(/###/g,"red").replace(/%%%/g,"23")
)
console.log(shapes);
like image 180
mplungjan Avatar answered Mar 02 '26 23:03

mplungjan


In lodash, you have a utility function mapValues

function replaceStringsInObject(obj, findStr, replaceStr) {
  return _.mapValues(obj, function(value){
    if(_.isString(value)){
      return value.replace(RegEx(findStr, 'gi'), replaceStr);
    } else if(_.isObject(value)){
      return replaceStringInObject(value, findStr, replaceStr);
    } else {
      return value;
    }
  });
}
like image 26
Meir Avatar answered Mar 02 '26 23:03

Meir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!