chrome.storage sorts object keys when it shouldn't?

292 views
Skip to first unread message

thdoan

unread,
Apr 22, 2018, 6:11:08 AM4/22/18
to Chromium-Extensions-Announce
Steps to reproduce:

  1. Open up any extension background page and enter this:

    chrome.storage.local.set({
      'obj': {
        'k1': 'one',
        'k2': 'two',
        'k10': 'ten'
      }
    });

  2. Now play it back:

    chrome.storage.local.get('obj', function(items) {
      for (var i in items['obj']) {
        console.log(i);
      }
    });
Output:

k1
k10
k2


Expected output:

k1
k2
k10

The expected output is based on the assumption that chrome.storage sorts string object keys the same way Chrome does (i.e., unsorted). You can try this in the Chrome console to see the difference:

items = {
 
'obj': {
   
'k1': 'one',
   
'k2': 'two',
   
'k10': 'ten'
 
}
};

// The code below outputs:
// k1
// k2
// k10
for (var i in items['obj']) {
  console
.log(i);
}

So it appears chrome.storage is sorting the objects keys in lexicographic order. The ES6/ES2015 spec states that string keys should be kept in the order in which they're provided (source), so I hope chrome.storage will be updated to follow the latest spec.

PhistucK

unread,
Apr 22, 2018, 9:52:58 AM4/22/18
to thdoan, Chromium-Extensions-Announce
Generally, if you want a sorted list, do not use an object, but an array.
Being sorted is an afterthought in objects.


PhistucK

--
You received this message because you are subscribed to the Google Groups "Chromium-Extensions-Announce" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extensions+unsub...@chromium.org.
To post to this group, send email to chromium-extensions@chromium.org.
Visit this group at https://groups.google.com/a/chromium.org/group/chromium-extensions/.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/3683bdd8-e5c1-4bdf-ac46-446fd63d6da8%40chromium.org.
For more options, visit https://groups.google.com/a/chromium.org/d/optout.

thdoan

unread,
Apr 22, 2018, 1:36:46 PM4/22/18
to Chromium-Extensions-Announce
Right, but I'm not commenting on developer best practice, I'm simply stating chrome.storage is not adhering to latest ES specs, which can be confusing to developers since V8 does not sort but the chrome.storage API does. It would help to be consistent; whether developers rely on object key order or not is auxiliary to the discussion ;-).
Reply all
Reply to author
Forward
0 new messages