尝试递归哈希对象中的值 [英] Trying to recursively hash values in object
问题描述
朋友.我正在尝试编写代码,对JSON文件中的所有值进行哈希处理,而不论文件结构如何,同时保留键和结构.我是javascript新手,遇到了一些麻烦.我的代码对big和baz的值进行了哈希处理,但并没有像我希望的那样递归地对cat和bar的值进行哈希处理.理想情况下,我希望单独散列数字和保留名称(big,foo等).非常感谢!请参阅下面的代码:
friends. I'm trying to write code that hashes all values in a JSON file, regardless of file structure, while preserving the keys and structure. I'm new to javascript, and am having some trouble. My code hashes the values of big and baz, but doesn't recursively hash the values of cat and bar like I want it to. Ideally, I want the numbers hashed and the names (big, foo, etc.) left alone. Thank you so much! See my code below:
var meow = {
big: 20,
baz: {
foo: {
cat: 3,
bar: 5
}
}
};
console.log(typeof(meow.baz.foo));
function hashobj(obj)
{
var valarray = Object.keys(obj);
var zer = valarray[0];
for(var i = 0; i < valarray.length; i++)
{
var vaz = valarray[i];
if(typeof(obj[vaz] != "object"))
{
obj[vaz] = sha256(obj[vaz] + buf);
}
if(typeof(obj[vaz]) == "object")
{
console.log("HERE");
hashobj(obj[vaz]);
}
}
}
hashobj(meow);
console.log(meow);
推荐答案
如果您要递归地执行此操作,我建议您使用一个通用的转换函数来处理递归对象结构并委托给提供的函数实际的工作叶节点的变换.
If you're looking to do this recursively, I would suggest using a generic transformation function that handles the recursive object structure and delegates to a supplied function the actual work of transforming the leaf nodes.
在此版本中, transform
函数可以完成所有繁重的工作.它对标量值调用提供的函数,并在对象和数组上递归调用自身,并使用新值重新创建原始结构.这是非常可重用的.
In this version, the transform
function does all the heavy lifting. It calls the supplied function on scalar values and recursively calls itself on objects and arrays, recreating the structure of the original with the new values. This is quite reusable.
我们通过传递 transform
一个对值进行sha256编码的函数来创建 hashObject
函数.
We create our hashObject
function by passing transform
a function which does the sha256 encoding of our values.
const transform = (fn) => (obj) =>
Array.isArray (obj)
? obj .map (transform (fn))
: Object (obj) === obj
? Object .fromEntries (Object .entries (obj)
.map (([k, v]) => [k, transform (fn) (v)])
)
: fn (obj)
const hashObj = transform ((n) => sha256 (String (n)))
const meow = {big: 20, baz: {foo: {cat: 3, bar: 5, qux: [1, 2, 3]}}};
// added to demonstrate arrays --------^
console .log (hashObj (meow))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://unpkg.com/js-sha256@0.9.0/src/sha256.js"></script>
这篇关于尝试递归哈希对象中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!