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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With