Creating a javascript hash table that keeps order?

I looked around, but nothing looks like what I'm looking for. I am trying to find out if you have a hash table that also keeps order, but at the same time gives you the advantage of accessing values ​​by key names (instead of index number).

Say I have a hash table:

var productsSelected = {
  cpu: "Core i7 2.4GHz",
  memory: "8GB",
  videoCard: "nVidia 6500-GTS",
  display: "27-inch LCD",
  extraBattery: "",
  antivirus: "",
  mouse: "Logitech 232",
  extendedWarranty: ""
}

I want to skip this object using Handlebars and display a list of products selected on the order confirmation page.

Products displayed in the order confirmation list must be in a specific order. I do not want the antivirus to appear at the top of the list, and then, for example, the CPU. I want it to be CPU-videoCard memory, etc.

I considered adding numbers to key names:

var productsSelected = {
  a100-cpu: "Core i7 2.4GHz",
  a110-memory: "8GB",
  a120-videoCard: "nVidia 6500-GTS",
  .
  .

But this is a very stupid way to do this.

There also

var productsSelectedArray = [
  {cpu: "Core i7 2.4GHz"},
  {memory: "8GB"},
  {videoCard: "nVidia 6500-GTS"},
  {display: "27-inch LCD"},
  {extraBattery: ""},
  {antivirus: ""},
  {mouse: "Logitech 232"},
  {extendedWarranty: ""}
]

, ? , , ?

-, , ( , - -), ( , ),

productsSelected.memory "8 "

productsSelected[1].value "8 "

productsSelected[1].key ""

- .

+4
3

, , . , , javascript:

http://dailyjs.com/2012/09/24/linkedhashmap/

, javascript, , . .

+3

, , ?

var keys = ['cpu', 'memory', 'videoCard'];

for (var i = 0, l = keys.length; i < l; i++) {
  console.log(productsSelected[keys[i]]);
};

, .

for (var i = 0, l = productsSelected.keys.length; i < l; i++) {
  console.log(productsSelected[productsSelected.keys[i]]);
};

DEMO

+1

- , Underscore?

:

productsSelectedArray = [
  {cpu: "Core i7 2.4GHz"},
  {memory: "8GB"},
  {videoCard: "nVidia 6500-GTS"},
  {display: "27-inch LCD"},
  {extraBattery: ""},
  {antivirus: ""},
  {mouse: "Logitech 232"},
  {extendedWarranty: ""}
];

, Underscore:

for (var i = 0, l = productsSelectedArray.length; i < l; i++) {
  console.log( _.keys(productsSelectedArray[i]) );
};

, Underscore.

for (var i = 0, l = productsSelectedArray.length; i < l; i++) {
  console.log( _.values(productsSelectedArray[i]) );
};
0

Source: https://habr.com/ru/post/1547391/


All Articles