Warm tip: This article is reproduced from serverfault.com, please click

Trying to recursively hash values in object

发布于 2020-12-01 19:03:11

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);
Questioner
Purrsephone
Viewed
0
Scott Sauyet 2020-12-02 04:01:27

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.

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.

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>