0

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?

4
  • That's an object, not an array. Commented Jul 8, 2021 at 9:19
  • you'll have to try to convert each value into integer and then if it succeed, add it to a new object, and finally, discard the old object and use the new one Commented Jul 8, 2021 at 9:22
  • That's also not JSON. Commented Jul 8, 2021 at 9:35
  • May i know how to convert the object to an array? Commented Jul 9, 2021 at 2:52

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice approach, Like it.
0

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

Comments

0
Object.entries().filter(([key,value]) => !Number.isNaN(Number.parseInt(value))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.