I would like to remove the word ".com" from my object. Currently I can convert the object into a string however my filter is not working.
const items = [
{
company: 'datadog.com'
},
{
company: 'google.com'
},
{
company: 'amazon.com'
},
{
company: 'facebook.com'
}
];
var names = items.map(function(item) {
return item['company'];
});
names.toString();
var filter = names.replace(".com", "");
console.log(filter);
CodePudding user response:
Simply use:
let names = items.map(item => item.company.replace(/[.]com$/, ''));
For each company domain name this returns the domain name with any final '.com'
sequence removed.
CodePudding user response:
Using the way you are doing it as a base, you can do something like this.
const items = [...youritems];
var names = items.map(function(item) {
return item['company'];
});
stringNames = JSON.stringify(names)
var filter = stringNames.replace(/.com/g, "");
filteredObject = JSON.parse(filter)
console.log(filteredObject)
But I don't think this is the safest way to go about it, or what you really want (it is not an array of objects). I would do something like this, using es6:
const items = [...youritems];
const newObject = items.map((item) => {
const companyNoCom = item["company"].replace(/.com/g, "")
newItem = {...item, company: companyNoCom}
return newItem
})
console.log(newObject)
This is safer to me, it keeps it an array of objects, and it is cleaner. It uses an arrow function and does not modify the underlying objects.