简体   繁体   中英

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

Cannot convert undefined or null to object.

Below is the code which I tried to use on the state data:

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:

Object
input1: {i: "ytuy"}
input2: {x: "tyutyu"}

My final goal is to have the JSON output as:

{
   "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 .

As mentioned in the comments, it is critical that you do not mutate the current object since this will mutate your component's 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 . So you'll want to make sure that the object exists before trying to map it.

since mutating the state object is not allowed in react js, here is the fix for my issue.

let obj = Object.assign({}, test );  // creates a brand new object
Object.keys(obj).forEach(key=>obj[key]=[obj[key]]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM