1

I have an array of objects, which may have certain characters that I wish to remove. In the example it is £. My array is structured as below:

const testArray = [
  { ASIN: 'ABC123', Rank: '£50', Sales: '£80' },
  { ASIN: 'ZYX123&', Rank: '£70', Sales: '£20' },
];

I wondered if I could use something like the replace function by taking the array, splitting it into a string, using replace and then joining it up again.

e.g. textArray.split(',').replace(/^\£/, '').join(',')

Someone showed me this code, but I couldn't get it to work:

myArray.map(item => {
      return Object.entries(item).reduce((agg, [key, value]) => {
        agg[key] = value.replace(/^\£/, '');
        return agg;
      }, {});
    });

Would my splitting into a string and rejoin method work? Is there a best practice way of doing this?

Jon
  • 501
  • 3
  • 18
  • Does this answer your question? [Replace all instances of a string within an object (and/or array) - JavaScript](https://stackoverflow.com/questions/23047211/replace-all-instances-of-a-string-within-an-object-and-or-array-javascript) – Heretic Monkey Feb 04 '21 at 16:03

2 Answers2

2

One option is to stringify the object, replace, then parse it:

const testArray = [
  { ASIN: 'ABC123', Rank: '£50', Sales: '£80' },
  { ASIN: 'ZYX123&', Rank: '£70', Sales: '£20' },
];

const newTestArray = JSON.parse(
  JSON.stringify(testArray).replaceAll('£', '')
);
console.log(newTestArray);

Could also transform the object by mapping with Object.fromEntries:

const testArray = [
  { ASIN: 'ABC123', Rank: '£50', Sales: '£80' },
  { ASIN: 'ZYX123&', Rank: '£70', Sales: '£20' },
];
const newTestArray = testArray.map(
  obj => Object.fromEntries(
    Object.entries(obj)
      .map(([key, val]) => [key, val.replaceAll('£', '')])
  )
);
console.log(newTestArray);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I am finding your code works great if I put in the test array you have above. But when I use my own array, I get this error: "TypeError: val.replaceAll is not a function" I cannot work out why it is doing that. I am importing the file, then running a bit of code on the imported data. For example, this is the last bit of code I run before using your map routine: `myArray.forEach((o, i) => (o.id = i + 1));` Any ideas what the issue might be? – Jon Feb 04 '21 at 17:38
  • If your environment doesn't support `replaceAll`, then either install a polyfill for it (recommended) or use the old-fashioned regex method instead. `.replace(/£/g, '')` – CertainPerformance Feb 04 '21 at 17:39
  • I now get this error: Uncaught TypeError: val.replace is not a function I'm doing this inside a class, if that makes any difference. – Jon Feb 04 '21 at 17:52
  • Sounds like one of your values is not a string. Make sure all values are strings, or convert them to strings before using `.replace`, or skip the transformation of non-strings, or something - figure out the logic you want. – CertainPerformance Feb 04 '21 at 17:53
  • Some of the values are not strings, since it is a CSV import and papaparse has a config to specify if some fields should be numbers or not. So maybe I should look at your stringify approach. – Jon Feb 04 '21 at 17:59
  • The stringify seems to work, thanks. I didn't try that at first because for some reason I am thinking that if you use JSON, it adds more bloat to the webpage load times. Am I write or completely wrong? – Jon Feb 04 '21 at 18:03
  • It depends on the situation. If you have data that isn't serializable, stringifying won't work. If you have a huge amount of data (like 10,000 objects), stringifying *might* have a negative impact on performance - or it might not, compared to the `Object.fromEntries` version (it'll depend on the environment). I'd prefer the `Object.fromEntries` version, but feel free to use whatever works for you. – CertainPerformance Feb 04 '21 at 18:05
  • I used the stringify because I don't know how to convert my imported string named object from a string to a number. For example, if I remove dynamicTyping: true from the papaparse config file, it will import the whole csv as a string. But then I am left with the question of how to convert an individual field from string to number. In this example, that would be Rank and Sales. – Jon Feb 04 '21 at 18:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228271/discussion-between-jon-and-certainperformance). – Jon Feb 04 '21 at 18:50
0

If you want to replace characters only in the values of the objects in array, you can try following code. It will iterate each object of the array one by one, get all keys of that object and iterate over those keys to replace the character in their values.

let keys;

testArray.map((obj)=>{

keys = Object.keys(obj);

keys.map((val)=>{

obj[val].replace(/a/g, "b");

})

})