Home > Net >  Validating array of object
Validating array of object

Time:11-25

How to validate the number whether it is negative or positive or decimal

 {items: [{id: 1, number: "9000"}, {id: 2, number: "80000"}, {id: 3, number: "1000"}]}

CodePudding user response:

I am not too sure what you are trying to do but if you want to filter the items array to only items where the number key is positive, you can try the code below:

const positiveNumbers = items.filter(item =>  item.number >=0);

If you want to create an object that has a positive and negative key and separate the items array you can try:

const categorizedNumbers = items.reduce((prev, next) => {
   const current =  next.number;
   if (current >= 0) {
     prev.positive.push(next);
   } else {
     prev.negative.push(next);
   }
}, {negative: [], positive []});

CodePudding user response:

We can find whether a number is positive or negative using the Number property using below script -

// Array of object
const data = {
  "items": [
    {
      "id": 1,
      "number": "9000"
    },
    {
      "id": 2,
      "number": "80000"
    },
    {
      "id": 3,
      "number": "-1000"
    }
  ]
}

// Check using .map
data.items.map((item: { id: number; number: string; isNegative?: boolean }) => item.isNegative = Number(item.number) < 0)

// Response
{
  "items": [
    {
      "id": 1,
      "number": "9000",
      "isNegative": false
    },
    {
      "id": 2,
      "number": "80000",
      "isNegative": false
    },
    {
      "id": 3,
      "number": "-1000",
      "isNegative": true
    }
  ]
} 

CodePudding user response:

const object = {
  items: [
    { id: 1, number: '9000' },
    { id: 2, number: '800000' },
    { id: 3, number: '1.0000' },
  ],
};

const isPositive = Obj => Obj.items.map(({ number }) => Number(number) > 0);
const isDecimal = Obj => Obj.items.map(({ number }) => number.includes('.'));

console.log(isPositive(object));
console.log(isDecimal(object));

  • Related