[英]How do you add new or update existing object properties using lodash only or plain javascript?
Say you have defined an object like: 假设您已经定义了一个对象,例如:
let myObject = {};
And you were going to add unknown properties that may or may not already exist. 您将添加可能不存在的未知属性。 To where myObject
would look more like: myObject
看起来更像:
{
foo: {
prop: 'SOME PROP NAME',
val: 'SOME VAL'
},
bar: {
prop: 'SOME PROP NAME',
val: 'SOME VAL'
},
baz: {
prop: 'SOME PROP NAME',
val: 'SOME VAL'
}
}
Keep in mind that foo.prop
and foo.val
may be set at different times. 请记住, foo.prop
和foo.val
可以在不同的时间设置。 With props and vals set at the same time I'd probably just use _.assign() and maybe it's as simple as that with an extra layer added. 在同时设置props和vals的情况下,我可能只使用_.assign(),也许就像添加一个额外的图层一样简单。
Assume there is a function like: 假设有一个类似的功能:
updateMyObject(e, attr, key) {
myObject[attr][key] = e.target.value;
}
Which obviously doesn't work 显然不起作用
I'm looking for a function that would work. 我在寻找, 将工作的功能。
Before adding a new key and value, you can check if myObject
contains attr
, otherwise create it. 在添加新的键和值之前,可以检查myObject
包含attr
,否则可以创建它。
updateMyObject(e, attr, key) {
if(!(attr in myObject))
myObject[attr] = {};
myObject[attr][key] = e.target.value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.