How to use ArrayList in JavaScript

0

I need to use a ArrayList in JavaScript to manipulate data and pass it through ajax.

For example: Set what type of transport it is, make, year and color.

eg var data = {"Automobile", "Nissan", "2010", "Red"}

Problem: What I need is to know how I can handle the data in this way and how to eliminate a certain row in the array, for example the one in the car I put up.

I hope to make myself understood.

    
asked by Ferny Cortez 28.01.2018 в 06:46
source

4 answers

3

Effectively brackets [] are used to define arrays while keys {} are for creating objects with properties.

For your case the most advisable thing is to create a car object just like you would with POO:

var coche = {"color": "rojo", "año": 2014}

You can learn how to use objects in JS here: link

I recommend you use the function when passing the data through ajax. JSON.stringify() to convert everything to JSON before sending and standardizing the data.

In your case:

var datos = ["Automovil", "Nissan", "2010", "Rojo"];

console.log(JSON.stringify(datos));

//devuelve: ["Automovil","Nissan","2010","Rojo"]

You can find more info on how to use the function: link

    
answered by 28.01.2018 / 13:43
source
1

To define an array in javascript the correct syntax is to enclose the elements in brackets ( [...] ), not between braces.

To eliminate an element from a certain position you can use the splice method, which receives as arguments the index (with base 0) from which you want to delete elements and the number of elements to be eliminated (in your case 1 ):

// Definición del array
var datos = ["Automovil", "Nissan", "2010", "Rojo"];

console.log("Array inicial: ", datos);

// Eliminar elemento "Automovil" (índice 0)
datos.splice(0, 1);

console.log("Resultado: ", datos);
    
answered by 28.01.2018 в 09:34
1

To work with objects and iterate through each of them in an array, you use the objects as elements of the array

var data = [
   {
   nombre: 'Eduardo',
   age: 17,
   programming: { value: !false, desc: '1 año de experiencia'}
   }, 
   {
   nombre: 'Jacinta',
   age: 18,
   programming: { value: true, desc: '3 años de experiencia'}
   }
];

data.forEach(objActual => console.log('Personas: ' +objActual.nombre));

var filtered = data.filter(objActual => objActual.age >= 18); // Obtener personas mayores de edad.

console.log('Hay ${filtered.length} personas mayores de edad.');
    
answered by 28.01.2018 в 14:39
0

According to the answers they gave me and the need I had, I was able to come up with a solution.

SOLUTION The solution is to combine both the JSON and the Arrays of Javascript objects.

var datos = {Automovil : [{Auto: [item1, item2, ...], Modelo: [item1, item2,..], Anio: [item1,item2,..]}]};

This way I could use:

datos.Automovil.Auto.push(item); //Agregar un nuevo Elemento
datos.Automovil.Auto.splice(0,1); //Eliminar según el indice 
    
answered by 28.01.2018 в 23:40