如何合并嵌套动态对象
我有这样的on change方法:
handleChange(e, fieldName, fieldType, index, parentEle) {}
在此内,我试图将值存储到一个名为 nestedobj 的全局对象中 我的参数是动态的
预期对象结构:
[parentEle]: {[index]: {[fieldName]: e.target.value}}
因此,在每个on Change之后,我的对象将是这样的:
fruit: {0: {fruitName: 'apple'}}
fruit: {0: {fruitId: 123}}
fruit: {1: {fruitName: 'orange'}}
fruit: {1: {fruitId: 456}}
car: {0: {carName: 'bmw'}}
car: {0: {carId: 789}}
car: {1: {carName: 'audi'}}
car: {1: {carId: 101}}
由于字段是动态的,这是我在做的事情:
const eachValue = { [index]: { [fieldName]: e.target.value } };
if (nestedObj?.[parentEle]?.[index]) {
nestedObj[parentEle][index] = Object.assign(
{},
nestedObj[parentEle][index],
eachValue[index]
);
}
else {
nestedObj[parentEle] = eachValue;
}
我要收到的是这样的
{
fruit: {1: {fruitName: 'orange', fruitId: 456}}
car: {1: {carName: 'audi', fruitId: 101}}
}
所以 每个值直接替换上一个元素的价值
是我期望的:
{
fruit: [{0: {fruitName: 'apple', fruitId: 123},
{1: {fruitName: 'orange', fruitId: 456}]
car: [{0: {carName: 'bmw', fruitId: 789},
{1: {carName: 'audi', fruitId: 101}]
}
您能指导我如何实现这一目标吗?
I have a onChange method like this:
handleChange(e, fieldName, fieldType, index, parentEle) {}
inside this I am trying to store the value into a global object called as nestedObj
my params are dynamic
expected object structure:
[parentEle]: {[index]: {[fieldName]: e.target.value}}
so after each onChange my object will be something like this:
fruit: {0: {fruitName: 'apple'}}
fruit: {0: {fruitId: 123}}
fruit: {1: {fruitName: 'orange'}}
fruit: {1: {fruitId: 456}}
car: {0: {carName: 'bmw'}}
car: {0: {carId: 789}}
car: {1: {carName: 'audi'}}
car: {1: {carId: 101}}
as fields are dynamic this is what I am doing:
const eachValue = { [index]: { [fieldName]: e.target.value } };
if (nestedObj?.[parentEle]?.[index]) {
nestedObj[parentEle][index] = Object.assign(
{},
nestedObj[parentEle][index],
eachValue[index]
);
}
else {
nestedObj[parentEle] = eachValue;
}
so what I am receiving is this:
{
fruit: {1: {fruitName: 'orange', fruitId: 456}}
car: {1: {carName: 'audi', fruitId: 101}}
}
so I am making the mistake in else part as assigning the eachValue to object directly replacing the previous element
what I expect is:
{
fruit: [{0: {fruitName: 'apple', fruitId: 123},
{1: {fruitName: 'orange', fruitId: 456}]
car: [{0: {carName: 'bmw', fruitId: 789},
{1: {carName: 'audi', fruitId: 101}]
}
can you please guide me how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如我之前提到的那样,我得到了解决方案,也说在否则中犯了一些错误的部分,因此进行了一些更改,现在正在
更新逻辑:
如果有人甚至可以建议一些更好的东西或者,如果可以简化,请更新
I got the solution, as I have mentioned earlier as well saying making some mistake in the else part of the condition, so made some changes and it is working now
updated logic:
if anyone can even suggest something better or if any simplification is possible then please update