Add element to the beginning of a key / value object

1

I have the following object:

var exemploLista = {
    "Igor": "exemplo1.jpg",
    "Joao": "exemplo2.jpg"
};

And I'm using this code to add an item to the object:

exemploLista["Lucas"] = "exemplo3.jpg";

But in this way, giving console.log(exemploLista) is returned:

  

Object {Igor: "example1.jpg", John: "example2.jpg", Lucas: "example3.jpg"}

And I would like the added element not to be at the end of array but at the beginning, and also if the element already exists in array it leaves its "position" and goes to the beginning. / p>

How can I do this?

    
asked by anonymous 26.01.2016 / 19:59

3 answers

5

The exemploLista that you are using and is created with the {...} notation is an object and not a array . In javascript objects are basically hash maps ({key: value}) and according to the specification that defines the syntax / language rules an object is "an unordered collection of properties with values".

So the way you built your exemploLista object there is no way to leave it in any desired order, you should consider that the values will always go out in random order, the fact that you have tested them and the values have been printed on the The order in which you put them in the object ( Object {Igor: "exemplo1.jpg", Joao: "exemplo2.jpg", Lucas: "exemplo3.jpg"} ) can be considered pure chance and can (read it goes) vary according to the browser even according to the version of it.

If you want to ensure order a good option is to use arrays true, an outline of how you could do what you want:

var exemploLista = [];
exemploLista[1] = {nome: "Igor", imagem: "exemplo1.jpg"};
exemploLista[2] = {nome: "Joao", imagem: "exemplo2.jpg"};

exemploLista[0] = {nome: "Lucas", imagem: "exemplo3.jpg"};

In the code above Lucas would be added last but would be in the first position of the array. To remove "Lucas" from the array if it already existed before being added you need to iterate over the exampleList array, check at each position if there is an object named Lucas, remove if there is and after the end of the loop add lucas in the desired position . Note that you would also have to rearrange the positions of the array so it does not look like empty elements. I will not add any more code and explanations because the answer is already quite long so I suggest you read the links about objects and arrays I passed so you can understand the difference and then post a new, more specific question if you still need it.     

26.01.2016 / 20:14
4

Your example is not an array - you are actually using indexed properties of a hashmap .

In order for exemploLista to be treated as an array , you should populate the variable as follows:

var exemploLista = [
    {nome: "Igor", imagem: "exemplo1.jpg"}, 
    {nome: "Joao", imagem: "exemplo2.jpg"}
];

In this case, to include an item in the first position use the array.unshift() method. According to the Mozilla documentation,

  

The unshift () method adds one or more elements at the beginning of an array and returns the number of elements (property length) updated.

Its use, therefore, would be as follows:

exemploLista.unshift({nome: 'Lucas', imagem: 'exemplo3.jpg'});

With the following result:

Notethevaluesofthe[0]registry.

Reference: link

    
26.01.2016 / 21:47
1

You can create a Class to encapsulate your list, then create a set method in the prototype of this Class that reorders the keys whenever a new element is inserted.

var Lista = function (obj) {
  //inserindo elementos iniciais
  if (obj) {
    for (var prop in obj) {
      this[prop] = obj[prop];
    }
  }
}

Lista.prototype.set = function (key, value) {
  //reordenando os elementos, a nova tupla deve ficar no topo.
  var obj = {};
  for (var prop in this) {
    if (this.hasOwnProperty(prop) && prop != key) {
      obj[prop] = this[prop];
      delete this[prop];
    }
  }
  this[key] = value;
  for (var prop in obj) {
    this[prop] = obj[prop];
  }
}

Lista.prototype.forEach = function (callback) {
  for (var key in this) {
    if (this.hasOwnProperty(key)) {
      callback(this[key], key);
    }
  }
}

var lista = new Lista({ "Igor": "exemplo1.jpg", "Joao": "exemplo2.jpg" });
lista.set("Lucas", "exemplo3.jpg");
lista.set("Joao", "exemplo4.jpg");
lista.forEach(function (value, key) {
  console.log(value, key);
});

I made a small update in the example above, implementing a forEach function for the list (which is actually a HashMap).

    
26.01.2016 / 21:13