[英]Add or replace object to array with dynamic key name in javascript (reactJS)
I have a number of select, when i onChange them i want to keep in componente state the selected value the onChange function i call do something like this:我有许多 select,当我对它们进行 onChange 时,我想保留在组件 state 中选择的值 onChange function 我称之为:
function validateVariations(event) {
console.log(event.target.value);
console.log(event.target.name);
setSelected((selected) => [
...selected,
{ [event.target.name]: event.target.value },
]);
.... //OTHER PROCESS
}
basically i add to state select an object like:基本上我添加到 state select 和 object 之类的:
[{Weight: "250"},{Pack: "Tin"}]
but using it a couple of time it fill up with the history changes like this:但是使用它几次它会填满这样的历史更改:
[{Weight: "250"},{Weight: "500"},{Weight: "250"},{Pack: "Tin"}, {Pack: "Card"}]
so i need to add the { [event.target.name]: event.target.value }
only if its not present an object with key [event.target.name]
, otherwise i need to replace it.所以我需要添加
{ [event.target.name]: event.target.value }
只有当它不存在带有键[event.target.name]
的 object 时,否则我需要替换它。
i tried using findIndex but im not able to reference to a dynamically named key我尝试使用 findIndex 但我无法引用动态命名的键
this is not working:这不起作用:
var i = data.findIndex(function(e) {
return e.[event.target.name] == event.target.name;
});
any elegant solution?任何优雅的解决方案?
Based on the format of your data, you could use this:根据您的数据格式,您可以使用:
var i = data.findIndex(function(e) {
return Object.keys(e)[0] === event.target.name;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.