[英]TypeError- Cannot convert undefined or null to object. Trying to convert state object values to json array string
While trying to fit the input form data to a JSON array string, I am getting an error尝试将输入表单数据拟合到 JSON 数组字符串时,出现错误
Cannot convert undefined or null to object.
无法将未定义或 null 转换为 object。
Below is the code which I tried to use on the state data:下面是我尝试在 state 数据上使用的代码:
const test = this.state.values;
Object.keys(test).forEach(key=>test[key]=[test[key]]);
When I do console.log(test)
the data is as below:当我执行
console.log(test)
时,数据如下:
Object
input1: {i: "ytuy"}
input2: {x: "tyutyu"}
My final goal is to have the JSON output as:我的最终目标是将 JSON output 设为:
{
"input1":[{"i":"ytuy"}],
"input2":[{"x":"tyutyu"}]
}
Can anyone suggest why I get this error?谁能建议我为什么会收到此错误?
It looks like what you are trying to do is to to each property value into a single-entry array.看起来您要做的是将每个属性值放入一个单条目数组中。 You can do that by mapping your object with
Object.fromEntries
and Object.entries
.您可以通过将 object 与
Object.fromEntries
和Object.entries
映射来做到这一点。
As mentioned in the comments, it is critical that you do not mutate the current object since this will mutate your component's state.正如评论中提到的,不要改变当前的 object 至关重要,因为这会改变组件的 state。
const test = { input1: {i: "ytuy"}, input2: {x: "tyutyu"} } const mapped = Object.fromEntries( Object.entries(test).map( ([key, value]) => [key, [value]] ) ); console.log(JSON.stringify(mapped));
That will print out那将打印出来
{"input1":[{"i":"ytuy"}],"input2":[{"x":"tyutyu"}]}
The particular error that you got sounds like perhaps this.state.values
is sometimes null
or undefined
and it not always an object
.您遇到的特定错误可能
this.state.values
有时是null
或undefined
的,它并不总是object
。 So you'll want to make sure that the object exists before trying to map it.因此,在尝试 map 之前,您需要确保 object 存在。
since mutating the state object is not allowed in react js, here is the fix for my issue.由于在反应 js 中不允许对 state object 进行变异,因此这是我的问题的修复。
let obj = Object.assign({}, test ); // creates a brand new object
Object.keys(obj).forEach(key=>obj[key]=[obj[key]]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.