需求是这样的,需要通过客户传过来的对象生成一个唯一标识,这样以后客户再传相同的对象,就不用记录到数据库中了. 想问有什么办法生成这样一个唯一表示么?
不知道具体需求,撸个参考实现吧(最好别直接复制过去用)
function uniqueId(obj) { const arr = [1, 2, 5, 10, 35, 33, 21, 16]; // 任意数量小于36的数,数量=生成标识字符串长度 let index = 0; Object.keys(obj).sort().forEach(it => { let val = obj[it]; if (typeof val === 'object') val = uniqueId(val); val = `${val}`; Array.prototype.forEach.call(val, (c, i) => { arr[index] = (arr[index] + val.codePointAt(i)) % 36; index++; index %= arr.length; }); }); return arr.map(c => c.toString(36)).join(''); } function test() { const objs = [ { aaa: 123 }, { bbb: 123, b: true, c: { cc: 'hello' }}, { aaa: 123 }, { c: { cc: 'hello' }, bbb: 123, b: true }, ]; const result = objs.map(it => uniqueId(it)); return result; } console.log(test());
hash(JSON.stringify(obj))
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
不知道具体需求,撸个参考实现吧(最好别直接复制过去用)
hash(JSON.stringify(obj))