JSON: Insert an element into a given index (or key)

Asked

Viewed 917 times

-1

var fields = [
    {
        "Category": "Computers",
        "Price": "125.60",
        "Book ID": "1",
        "Book Name": "Computer Architecture"
    },
    {
        "Book ID": "2",
        "Category": "Programming",
        "Price": "56.00",
        "Book Name": "Asp.Net 4 Blue Book"
    },
    {
        "Price": "210.40",
        "Book ID": "3",
        "Category": "Science",
        "Book Name": "Popular Science"
    }
];

if(fields.length > 0){
    var newField = [];
    for(var i = 0; i < fields.length; i++){
        var field = fields[i];
        fields[i]["abobora"] = 'abobora teste';
    }
    var newField = fields;
    console.log(newField);
} 
  • How do I add in the second position of each element? The above example always adds in the last element of each object

Example here: https://jsfiddle.net/a6dx81fy/

  • I wanted the object to be added to a given index, as an example below:

    var fields = [
    {
        "Category": "Computers",
        "Price": "125.60",
        "abobora": 'abobora teste', <- gerar nesse index
        "Book ID": "1",
        "Book Name": "Computer Architecture"
    },
    {
        "Book ID": "2",
        "Category": "Programming",
        "abobora": 'abobora teste',  <- gerar nesse index
        "Price": "56.00",
        "Book Name": "Asp.Net 4 Blue Book"
    },
    {
        "Price": "210.40",
        "Book ID": "3",
        "abobora": 'abobora teste', <- gerar nesse index
        "Category": "Science",
        "Book Name": "Popular Science"
    }];
    
  • carlos, do not abandon your questions. Mark an answer as the right one, or if none solved, question. Abandoning questions is not part of the community’s purpose. Abs!

3 answers

0

You can add the property and use the second parameter of JSON.stringify to turn the object into String and maintain an order in your JSON view, passing an Array with the properties in the order you want them to be displayed. Soon after, you use JSON.parse again to transform the String in Object.

var field = {
    "Category": "Computers",
    "Price": "125.60",
    "Book ID": "1",
    "Book Name": "Computer Architecture",
    "abobora": 'abobora teste'
};

field = JSON.parse(JSON.stringify(field, ["Category", "Price", "abobora", "Book ID", "Book Name"]));

console.log(field);

This is not necessarily "changing the index" because in objects JSON no numerical indices to be accessed as in Array, unless you create them for that purpose. What it does is simply change the display order.

0

Your question is ambiguous, there are two interpretations, the first is that you want to insert a new key/value pair into the object, but want to add in a specific position and not simply add the new key/value pair.

The second interpretation is that you want to add a new object to the object array, but you want to add it not at the end, but at a specific index.

For the first one (which makes no sense, because in the object the access to the values depends on the key and not the position in which they are, the role of "chained list" in Javascript is Array):

Simply create a new object, like this:

let objAntigo = { category: "categoria", price: 10, bookId: 3 };

let novoObj = {
  category: objAntigo.category,
  abobora: "abobora",
  price: objAntigo.price, 
  bookId: objAntigo.bookId
}

For the second interpretation, you can use the splice() method of the Javascript array, thus:

let arrayAntigo = ["objeto um", "objeto dois", "objeto tres"];
let removidos = arrayAntigo.splice(1, 0, "objeto quatro");

console.log(arrayAntigo) // ["objeto um", "objeto quatro", "objeto dois", 
"objeto tres"]
  • splice() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

0

You can restructure the object by making a loop for in concatenating the values and inserting the new "pumpkin" key when the loop is in the second key making a concatenation into a variable. Then just use JSON.parse to convert the variable to object in the array object newField.

Behold:

var fields = [
    {
        "Category": "Computers",
        "Price": "125.60",
        "Book ID": "1",
        "Book Name": "Computer Architecture"
    },
    {
        "Book ID": "2",
        "Category": "Programming",
        "Price": "56.00",
        "Book Name": "Asp.Net 4 Blue Book"
    },
    {
        "Price": "210.40",
        "Book ID": "3",
        "Category": "Science",
        "Book Name": "Popular Science"
    }
];

if(fields.length > 0){
   var newField = [];
   for(var i = 0; i < fields.length; i++){
      var field = fields[i];
   
      var novo = "";
      var x=0;
      for(var idx in field){
         var item_atual = '"'+idx+'":"'+field[idx]+'",';
         novo += item_atual + (x < 1 || x > 1 ? '' : '"abobora": "abobora teste",');
         x++;
      }
   
      novo = '{'+novo.substring(0,novo.length-1)+'}'; // removo a última vírgula
   
      newField[i] = JSON.parse(novo); // crio o objeto json
   
   }
   console.log("Original", fields);
   console.log("Novo", newField);
   console.log(newField[0]["abobora"]);
}

Browser other questions tagged

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