-2
    {
        "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?

  • 1
    unclear what you are actually asking. "Save" means what? What is the expected output. Answer is going to be filter and probably map. – epascarello Oct 06 '22 at 14:09
  • Welcome to stackoverflow! But we are no coding service. You first have to research for your own and tell what you have tried and add a [minimal reproducable example](https://stackoverflow.com/help/minimal-reproducible-example) of that try, at best in a [stack snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do). See [how to ask](https://stackoverflow.com/help/how-to-ask) – biberman Oct 06 '22 at 14:10
  • https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes – epascarello Oct 06 '22 at 14:11

2 Answers2

0

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)
Abdellah Hariti
  • 657
  • 4
  • 8
0

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)
Devendra
  • 1
  • 2