0

I'm pushing on objects while clicking on button with Reactjs. Initially i'm having three type of objects like "LOCAL", "GLOBAL" and "MAIN". I'm passing these names as parameters in onclock callback. How to an avoid to insert duplicates with reactJs?

My render code,

<div>
   <input type="checkbox" onClick={this.checkedIn.bind(this, "LOCAL", "12")} />
   <button type="checkbox" onClick={this.checkedIn.bind(this, "GLOBAL", "15")} />
   <button type="checkbox" onClick={this.checkedIn.bind(this, "MAIN", "11")} />
  <button type="checkbox" onClick={this.checkedIn.bind(this, "MAIN", "13")} />
</div>

onclick event

var objectVale = [];
checkedIn(type, value) {
  objectVale.push({
    type:type,
    value:[value]
  })
}

Expecting output,

[
  {
    "type":"LOCAL",
    "value":[12]
  },
  {
    "type":"GLOBAL",
    "value":[15]
  },
  {
    "type":"MAIN",
    "value":[11, 13]
  }
]

2 Answers 2

1

You could try something like this:

var objectVale = [];
checkedIn(type, value) {

    var index = objectValue.findIndex(function(obj){ return obj.type === type; });
    if(index === -1){ // Object with the specific type not found.
        objectValue.push({
            type:type,
            value:[value]
        })
    } else { // Object with the specific type found. So push only the value.
        objectValue[index].value.push(value)
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Also I'd suggest using .find. This way you will not have to fetch object using index.
@Rajesh I would say that both ways are valid.
Also, if i uncheck that checkbox, the unchecked checked should be removed. I tried this way, var mainValues = []; mainValues.push(value); var sameValueIndex = mainValues.indexOf(value); mainValues.splice(sameValueIndex, 1); But its not giving correct result
1

Issue is you are pushing value for every click event. Instead, first lookup array and find the necessary object using type and then push value to this object's value array.

var o = objectVale.find(function(x) {
  return x.type === type;
})

if (o) {
  o.value = o.value || [];
  o.value.push(value);
} else {
  objectVale.push({
    type: type,
    value: [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.