JSON: Inserting an element in a given index (or key)

0
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 I've always added adds in the last element of each object

Example here: link

  • I wanted the object to be added in 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"
    }];
    
asked by anonymous 19.04.2018 / 19:48

3 answers

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 you want to add it 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 array of objects, but you want to add it not at the end, but at a specific index.

For the first one (which does not make sense since in the object the access to the values depends on the key and not on the position they are in, the role of "list chained" 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, like this:

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"]
    
19.04.2018 / 20:26
0

You can add the property and use the second parameter of JSON.stringify  to transform the object to String and keep an order in the display of your JSON by passing an Array with the properties in the order that you want them to be displayed. Soon after, you'll use JSON.parse again to turn String into 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 "change the index", because in JSON objects there are no numerical indexes to be accessed as in Array , unless you create them for this purpose. What this does is simply change the display order.

    
19.04.2018 / 20:18
0

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

See:

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"]);
}
    
19.04.2018 / 23:59