如何根据对象生成一个唯一标识
发布于 4 年前 作者 a1292717155 5455 次浏览 来自 问答

需求是这样的,需要通过客户传过来的对象生成一个唯一标识,这样以后客户再传相同的对象,就不用记录到数据库中了. 想问有什么办法生成这样一个唯一表示么?

2 回复

不知道具体需求,撸个参考实现吧(最好别直接复制过去用)

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))

回到顶部