React-Native - Object.assign 子项更改

React-Native - Object.assign children change

本文关键字:assign Object React-Native      更新时间:2023-09-26

如果这个问题仍然存在,但我搜索了它,但没有找到解决方案。此外,我无法从Developer.Mozilla网站上获得任何提示,其中Objects.assignment等描述得很好。

问题:

如何更改对象的子项?与我在下面描述的输出完全一样。

示例代码

var obj= {test: [{a: 2}, {b: 3}]};
var newChildren = [{a: 3}, {b: 5}, {c: 1}];
//I read the obj key value by the following:
var objKey = Object.entries(obj)[0][0]
//Here i want to have some code to get the following result
//My momentary regarding to @webdeb
var output = Object.assign({}, {objKey: newChildren})
actual output: // {objKey: [{a: 3}, {b: 5}, {c: 1}]}
wanted output: // {test: [{a: 3}, {b: 5}, {c: 1}]}

我没有其他选择来获取其他格式的代码,因此需要以我描述的方式进行"输入"。我需要将objKey设置为变量,因为我的代码中有多个键,我必须为多个子级设置。(做一些过滤器的东西)

感谢您的帮助

BR乔纳森

首先,不要使用 Object 作为变量 Name。

好的,假设对象现在已obj

无需修改obj

var newObj = Object.assign({}, obj, {test: newChildren})

或者只是,(修改obj

obj.test = newChildren

这是你要找的吗?

以下解决方案给了我想要的确切结果:

obj[objKey] = newChildren;
console.log(obj) // {test: [{a: 3}, {b: 5}, {c: 1}]}

我针对以下问题采取了这个解决方案:

如何将键/值对添加到 JavaScript 对象?

对我来说,重要的是将object-key作为一个变量。所描述的解决方案使我可以选择向more添加一个值,而不仅仅是一个static键。