Ad

Push Dynamically Coming Id's And Value's In Javascript

- 1 answer

The question may seem a little confusing so let me explain the situation, i have a category field, that when it's chosen, i get data from api based on that category, for example when you choose category A, you may get the id's 1 to 3 or when you chose category B, you get the id's of 8 to 11, so what i'm trying to do is create a Filter array that pushes these values with id's so when user types something like sth in input with the id of 1, this objects gets pushed to the array, something like below:

Filters = [ 
   {
     id:1,
     value: sth
   }
]

so what i have basically done is something like this:

this.props.Filters.map(item => (
     <div className="from" key={item.id} id={item.id} >
          <span className="title">{item.feature}</span>
          <input type="text" placeholder="..." id={item.id} onChange={FilterPush}></input>
     </div>
))

and the function is:

const Filters = []
const FilterPush = (e) => {
      const filter = {
           id: e.currentTarget.getAttribute("id"),
           value: e.currentTarget.value
       }
       Filters.push(filter)
}

the problem i'm having here is every time a user is typing something an object is pushed to Filters, so when user tries to type sth the Filter gets equal to:

Filters={
    {id:1,value:s},
    {id:1,value:st},
    {id:1,value:sth}
}

but i want it to be equal to this

Filters={
    {id:1, value:sth}
}

bear in mind that the id's are dynamic and i don't know them, and there's not just one input, i mean we can have 3 inputs with diffrent id's that should get send to the server.

Ad

Answer

Just filter out existing id:

const FilterPush = (e) => {
      let id = e.currentTarget.getAttribute("id")
      const filter = {
           id,
           value: e.currentTarget.value
       }
       Filters = Filters.filter(item => item.id !== id) // filter out existing id
       Filters.push(filter)
}
Ad
source: stackoverflow.com
Ad