Add element at the beginning of a key object/value

Asked

Viewed 10,597 times

2

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 that way, by giving console.log(exemploLista) is returned:

Object {Igor: "exemplo1.jpg", Joao: "exemplo2.jpg", Lucas: "exemplo3.jpg"}

And I would like the added element not to be at the end of array and yes at the beginning, and also if the element already exists in the array he step out of his "position" and go to the beginning.

How can I do that?

3 answers

5


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

So the way you built your object exemploLista there is no way to leave it in any desired order, you must consider that the values will always come out in random order, the fact that you have tested and the values have been printed in 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 will) vary according to the browser even according to the version of the same.

If you want to ensure the order a good option is to use arrays true, an outline of how you could do whatever 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 above code 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 it was added you need to iterate over the sample arrayList, check at each position if there is an object with the name Lucas, remove if it exists and after the end of the loop add Ucas at the desired position. Note that you would also have to rearrange the positions of the array so that it does not become empty elements. I will not add more code and explanations because the answer is already quite long so I suggest you read the links about objects and arrays that I passed so that you understand the difference and then post a new more specific question if you still need.

4

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

Why exemploLista be treated as a array, you must popular 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 method array.unshift(). According to the Mozilla documentation,

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

Its use, therefore, would be as follows:

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

With the following result:

inserir a descrição da imagem aqui

Note the values of the record [0].

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

1

you can create a Class to encapsulate your list, then create a method set on the prototype of this Class reordering 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 performed a small update in the example above, implementing a foreach function for the list (which is actually a Hashmap).

  • 1

    Although it’s a great solution I don’t think it’s a good idea for you to use the term Class to refer to the construction function Lista, after all javascript has no classes and this will probably confuse the user who asked the question (see that he was already confusing objects with arrays) and other people.

  • It worked, but how could I treat this data? I’m trying so: listaExemplo = new Lista({"Igor": "exemplo1.jpg", "Joao": "exemplo2.jpg"}); but while using $.each(listaExemplo, function(index, value) {
 $("body").append(index+" - "+value);
 }); the following is returned: Igor - example1.jpgJoao - example2.jpgset - Function (a,t){var e={};for(var o in this)this.hasOwnProperty(o)&&o!= a&&(e[o]=this[o],delete this[o]);this[a]=t;for(var o in e)this[o]=e[o]}

  • 1

    @Brunorb, I understand that it is not correct to call this type of class structure, but in ECMA5, this type of structure is the closest to a class, so much so that in this Guide: Introduction to Object-Oriented Javascript, the author calls it Classe, perhaps because it believes that for didactic purposes it is valid to do this corelation between OO and Prototype Orientation.

  • 1

    @Igor, as pointed out by Bruno, you cannot guarantee the order of the properties of an object, on the other hand, the object Map secured this order, but it is only supported by the latest versions of Browsers, what you can do is use the above implementation to implement your own HashMap with the necessary characteristics and methods.

  • @Tobymosque If I implement the example you posted, it will work in all browser versions or only the latest ones?

  • @Tobymosque another question. If I wanted, instead of leaving the object at the beginning, leave it at the end, what would be the adaptation in the code? Thank you!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.