简体   繁体   English

javascript - 如何从 FormData object [object Object] 中获取嵌套的 object

[英]javascript - How to get nested object from a FormData object [object Object]

I want to get the entire nested object (with all the props) of a value that is stored in a FormData.我想获取存储在 FormData 中的值的整个嵌套 object(包含所有道具)。 This is possible?这个有可能?

Example例子

 const formData = new FormData(); formData.append('k1', 123); formData.append('k2', 'ABC'); formData.append('k3', { a: 1, b: '2' }); data = {}; formData.forEach((value, key) => { console.log(`Key: ${key}`, { key, value, type: typeof(value), getResult: formData.get(key), getAllResult: JSON.stringify(formData.getAll(key)) }); data[key] = value; }); console.warn('Final result', { data });
 .as-console-wrapper { max-height: 100%;important; }

There is a way to capture the keys and values of the k3 without using jQuery or any external library?有没有一种方法可以在不使用 jQuery 或任何外部库的情况下捕获k3的键和值?

Ok, so this isn't quite what you're after, but here goes.好的,所以这不是您想要的,但是可以了。 If you want to pass in an object for your k3 value, then you'll need to stringify it first.如果您想为您的k3值传递 object,那么您需要先将其stringify You'll then need to parse it back out to an object wherever you want to use it.然后,您需要将其解析回 object,无论您要在何处使用它。 I've updated your code above to stringify the value, and attempt to parse it back out in your debugging (just so that you can see it)我已经更新了您上面的代码以将值字符串化,并尝试在您的调试中将其解析回来(只是为了您可以看到它)

 const formData = new FormData(); formData.append('k1', 123); formData.append('k2', 'ABC'); formData.append('k3', JSON.stringify({ a: 1, b: '2' })); data = {}; formData.forEach((value, key) => { console.log(`Key: ${key}`, { key, value, type: typeof(value), rawResult: formData.get(key), potentialObjResult: (function(val){ let potential = undefined; try { potential = JSON.parse(val); } catch(ex){ console.log('could not parse: <' + val + '> as JSON'); } return potential; })(formData.get(key)) }); data[key] = value; }); console.warn('Final result', { data });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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