I have text inputs that are writing to a model. I want those objects to write to the model and update if the key exists.
For example: If I submit,
Id: "1", Value: "Foo"
And I update it with a new value:
Id: "1", Value: "Bar"
My array should read:
0 { Id: "1", Value: "Bar"}
Not
0 { Id: "1", Value: "Foo"}
1 { Id: "1", Value: "Bar"}
Example here: JSFiddle
<div id="wrapper">
<div>
<input id="1" type="text" value="input_1">
<button>Button 1</button>
</div>
<br>
<div>
<input id="2" type="text" value="input_2">
<button>Button 2</button>
</div>
<br>
<div>
<input id="3" type="text" value="input_3">
<button>Button 3</button>
</div>
<br>
</div>
jQuery -- will add to the array but not sure how to update if key exists. Looked at other examples but still not getting it
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
if(obj.pairs.length > 0){
$.each(obj.pairs, function(i, pair) {
if($(this).id !== input_id){
obj.pairs.push(keyValuePairs);
return false;
} else {
obj.pairs.splice(i, 1);
obj.pairs.push(keyValuePairs);
}
});
} else {
obj.pairs.push(keyValuePairs);
}
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
console.log(obj);
});
Try this https://jsfiddle.net/y6rgm7z8/93/
$(document).ready(function() {
var obj = {
pairs: []
}
$("button").on("click", function() {
var keyValuePairs = {
id: "",
value: ""
}
var input_id = $(this).prev().prop('id');
var dynamic_value = $(this).prev().prop('value');
var pair = obj.pairs.find(item => item.id === input_id)
if(pair){
pair.value = dynamic_value;
} else {
keyValuePairs.id = input_id;
keyValuePairs.value = dynamic_value;
obj.pairs.push(keyValuePairs);
}
console.log(obj);
});
});
The find() method executes the function once for each element present in the array:
The find() is better for performance than each().
And we don't need splice() with push() for updating because after find() we have link to the object, so we can change the value.
If find() returns undefined we will push the new object to the array
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments