Jon
Jon

Reputation: 509

Replace character in array of objects

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?

Upvotes: 1

Views: 2358

Answers (2)

malicious.dll
malicious.dll

Reputation: 63

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");

})

})

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371029

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);

Upvotes: 2

Related Questions