Reputation: 1734
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]
}
]
Upvotes: 0
Views: 3582
Reputation: 53958
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)
}
}
Upvotes: 1
Reputation: 24915
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]
})
}
Upvotes: 1