Reputation: 9
I want to ask how do I remove strings from data. Lets say I have a data:
var data = {DeviceID: "101", ManufacturerID: "9", ManufacturerName: "Toshiba", Device Name: "Toshiba - Tecra R950", Price: "200"};
how do I remove ManufacturerName
and Device Name
because they do not have numbers?
Upvotes: 0
Views: 690
Reputation: 63524
The simplest method - if you're happy with mutating the object rather than creating a new one - is to iterate over the object properties, and try to coerce each value to a number. If it's not a number remove the property.
const data = { DeviceID: '101', ManufacturerID: '9', ManufacturerName: "Toshiba", 'Device Name': 'Toshiba - Tecra R950', Price: '200' };
for (let key in data) {
if (!Number(data[key])) delete data[key];
}
console.log(data);
Upvotes: 1
Reputation: 1725
Object.entries().filter(([key,value]) => !Number.isNaN(Number.parseInt(value))
Upvotes: 0
Reputation: 6390
You can do it like this-
const data = {DeviceID: "101", ManufacturerID: "9", ManufacturerName: "Toshiba", DeviceName: "Toshiba - Tecra R950", Price: "200"};
const res = Object.fromEntries(
Object.entries(data).filter(([key, value]) => !isNaN(Number(value)))
);
console.log(res);
Upvotes: 0