OnePlusTwo
OnePlusTwo

Reputation: 23

Javascript Array with Dynamic Editable Objects and values

I have to track cars and car types/colors without a database and I'm looking for a way to create an array with objects that I can update and delete, then be able to call the array.

So maybe something like this where I can add/edit/delete any of the object properties by car:

let cars = [];
cars['ferrari'] = "red";
cars["lambo"] = "white";
cars["bentley"] = "silver";

I know how to get the value with this example:

showcolor = 'ferrari';
alert(cars[showcolor]);

Is it possible to push a new object into this array and/or update a single car and change the color for that car with a function that looks for the object value 'ferrari' and changes its color to 'black'? Also if I wanted to create an alert to show the contents of the array, how can I do that?

Upvotes: 2

Views: 58

Answers (4)

stalkert
stalkert

Reputation: 26

You can use Map from ES20015  standart.
let cars = new Map([
    ['ferrari',   'red'],
    ['lambo', 'white'],
    ['bentley',   'silver']
]);

console.log(cars.get('ferrari')) // red

You can also add car: cars.set('bmw','black');

console.log(cars.get('bmw')) // black

For updating: cars.set('bmw','blue');

Use for ... of for alerts data:

for(let car of cars) { alert(car); }

Upvotes: 0

Wyck
Wyck

Reputation: 11750

Or use an array, but let each element of the array be an object.

let cars = [];
cars.push({ make: 'ferrari', color: 'red' });
cars.push({ make: 'lambo', color: 'white' });
cars.push({ make: 'bentley', color: 'silver' });
console.log(JSON.stringify(cars));

// Make the lambo black instead of white.
cars.find(car => car.make == 'lambo').color = 'black';
console.log(JSON.stringify(cars));

Output is:

[{"make":"ferrari","color":"red"},{"make":"lambo","color":"white"},{"make":"bentley","color":"silver"}]
[{"make":"ferrari","color":"red"},{"make":"lambo","color":"black"},{"make":"bentley","color":"silver"}]

Note the lambo color changed.

Upvotes: 1

Osama
Osama

Reputation: 3040

Use object oriented JavaScript

class Cars{
  constructor(color) {
    this.color= color;
  }
  function getColor(){
    console.log(this.color);
  }

Then create an instant of it

var mycar = new Cars('Blue');
mycar.getColor();

Upvotes: 0

slider
slider

Reputation: 12990

You shouldn't use an array. Use an object:

let cars = {}; // {} creates a new object

cars['ferrari'] = "red";
cars["lambo"] = "white";
cars["bentley"] = "silver";

// add new car
cars['bugatti'] = 'blue';

// update car
cars['lambo'] = 'green'

console.log(cars);

Upvotes: 0

Related Questions