N
N
netz-sanya2017-07-15 15:52:48
JavaScript
netz-sanya, 2017-07-15 15:52:48

Why does JSON.stringify produce an empty result?

var orb = {};
var abc = JSON.parse(localStorage.getItem("itemData"));
for (var key in abc) {
  for (var i = 0; i < abc[key].length; i++) {
    var p = {};
    p["p"] = abc[key][i].p;
    p["id"] = abc[key][i].id;
    Tools.sha1(abc[key][i].m).then(function(digest) {
      orb[digest] = p;
    });
  }
}
console.log(JSON.stringify(orb));

This code outputs:
{}
But if you execute in the browser console first:
var orb = {};
var abc = JSON.parse(localStorage.getItem("itemData"));
for (var key in abc) {
  for (var i = 0; i < abc[key].length; i++) {
    var p = {};
    p["p"] = abc[key][i].p;
    p["id"] = abc[key][i].id;
    Tools.sha1(abc[key][i].m).then(function(digest) {
      orb[digest] = p;
    });
  }
}

and then the json is generated. Objects 10000+ Why is this, and how to fix it?
console.log(JSON.stringify(orb));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily, 2017-07-15
@VasiliyIsaichkin

let Tools = {};

function hex(buffer) {
  let hexCodes = [];
  let view = new DataView(buffer);
  for (let i = 0; i < view.byteLength; i += 4) {
    let stringValue = view.getUint32(i).toString(16);
    let padding = '00000000';
    hexCodes.push((padding + stringValue).slice(-padding.length));
  }
  return hexCodes.join('');
}

Object.assign(Tools, {
  sha1: async (str) => hex(await crypto.subtle.digest('SHA-1', new TextEncoder('utf-8').encode(str)))
});


(async () => {
  let result = await Tools.sha1('Blabla1a');
  console.log(result);
})();

And no stress with the progress engine :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question