Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim property of specific object inside array of objects

Tags:

javascript

Question: How to iterate through an array of objects and trim-specific property of an object?

Need to update the array of objects, to update every property in objects inside an array.

I need to delete white spaces (trim) accountId and handlerId properties in every object.

Here is a code example of what I tried:

// This is an array of objects
var data = [
  { 
    Company: "Church Mutual",
    accountId: "1234567  ",  <======= need to trim()
    accountName: "Test123",
    handlerId: "1111111  ",   <======= need to trim()
    lineOfBusiness: "WC",
    selectedState: "NY",
    tpa: "No",
  },
   { 
    Company: "Church Mutual",
    accountId: "1234567  ",
    accountName: "Test123",
    handlerId: "1111111  ",
    lineOfBusiness: "WC",
    selectedState: "NY",
    tpa: "No",
  }
];

var newData = data.forEach(i => {
 data[i].accountId.trim()
})

Any advice or help is welcome.

like image 918
Mark James Avatar asked Nov 21 '25 14:11

Mark James


2 Answers

You can use forEach and Object.entries

var data = [
  { 
    Company: "Church Mutual",
    accountId: "1234567  ",
    accountName: "Test123",
    handlerId: "1111111  ",
    lineOfBusiness: "WC",
    selectedState: "NY",
    tpa: "No",
  },
   { 
    Company: "Church Mutual",
    accountId: "1234567  ",
    accountName: "Test123",
    handlerId: "1111111  ",
    lineOfBusiness: "WC",
    selectedState: "NY",
    tpa: "No",
  }
];

data.forEach(e => {
  Object.entries(e).forEach(([key,value])=>{
    e[key] = value.trim()
  })
})

console.log(data)
like image 85
Code Maniac Avatar answered Nov 24 '25 03:11

Code Maniac


You want to use map:

var data = [
  { 
    Company: "Church Mutual",
    accountId: "1234567  ",  
    accountName: "Test123",
    handlerId: "1111111  ",   
    lineOfBusiness: "WC",
    selectedState: "NY",
    tpa: "No",
  },
   { 
    Company: "Church Mutual",
    accountId: "1234567  ",
    accountName: "Test123",
    handlerId: "1111111  ",
    lineOfBusiness: "WC",
    selectedState: "NY",
    tpa: "No",
  }
];

var newData = data.map(o => {
 o.accountId = o.accountId.trim();
 o.handlerId = o.handlerId.trim();
 return o;
});

console.log(newData);
like image 37
David Avatar answered Nov 24 '25 04:11

David



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!