Home > other >  Filtering JSON and grabbing input value
Filtering JSON and grabbing input value

Time:10-07

    {
        "input": " 31623344601",
        "status": "valid",
    },
    {
        "input": " 31623774921",
        "status": "invalid"
    }

How can I save numbers that have a VALID status? I have a JSON response and I would like to save only valid numbers. How can I filter?

CodePudding user response:

Let's imagine your input is jsonData. First we (1) JSON.parse it to turn into a js array, then run a filter (2) with a predicate that returns true for valide items, then map each item to its input (number) property to end up with an array of valid numbers.

let jsonData = `[
  {
    "input": " 31623344601",
    "status": "valid"
  },
  {
    "input": " 31623774921",
    "status": "invalid"
  }
]`
    
 let validNumbers = JSON.parse(jsonData) // 1
 .filter(item => item.status == "valid") // 2
 .map(item => item.input) // 3
 
 console.log(validNumbers)

CodePudding user response:

you can simply do something like this to resolve your problem. I have used filter(), but there are also other methods to do it.

const res = [
    {
        "input": " 31623344601",
        "status": "valid",
    },
    {
        "input": " 31623774921",
        "status": "invalid"
    }
];

var filteredRes = []

res.filter((data) => {
  if(data.status === 'valid'){
    filteredRes.push(
      data.input
    )
  }
})

console.log(filteredRes)

  • Related