Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object as a type of mini database?

Is it possible to use a JavaScript object as a type of mini database? I often find myself needing a kind of database structure when I'm coding in JS but it feels like overkill to use an actual database like MySQL (or similar).

As an example, let's say I need to structure this data as a JS object:

Object idea: Stuff to sell
Items to sell: The junk in the garage
Object structure: List all items including item name, item condition, and item value

In order to make this into a JS object I would maybe write:

var stuffToSell = {};

Then my first item would maybe look like:

var stuffToSell = {
    item : "Coffee Maker",
    condition : "Good",
    price : 5
};

Now to me this seems like I'm on the right track, until I come to add another item and I end up having to use the properties item, condition, and price again in the same JS object — which feels wrong? — or is it?? At this point my brain keeps shouting the word "ARRAY!" at me but I just can't see how I can use an array inside the object, or an object inside an array to achieve what I want.

My end goal (in this simplified example) is to be able to then use object-oriented syntax to be able to access certain items and find out specific information about the item such as price, condition etc. For example if I want to know the price of the "coffee maker" I would like to write something like:

stuffToSell["coffee maker"].price

...and then the result above should be 5.

I feel like I'm on the right track but I think I'm missing the array part? Could someone please tell me what I'm missing or maybe what I'm doing completely wrong! And also if it is wrong to have duplicate property names in the same JS object? For example, is it okay to have:

var stuffToSell = {
item : "Coffee Maker",
price : 5,
item : "Mountain Bike",
price : 10,
item : "26 inch TV",
price : 15
};

...it seems wrong because then how does JS know which price goes with which item??

Thanks in advance :)

like image 810
Ben Clarke Avatar asked Oct 24 '25 16:10

Ben Clarke


2 Answers

You're definitely on the right track!

A lot of people will refer to what you're talking about as a hash.

Here's my suggested structure for you:

var store = {
        coffee_maker: {
                id: 'coffee_maker',
                description: "The last coffee maker you'll ever need!",
                price: 5,
        },
        mountain_bike: {
                id: 'mountain_bike',
                description: 'The fastest mountain bike around!',
                price: 10,
        },
        tv: {
                id: 'tv',
                description: 'A big 26 inch TV',
                price: 15,
        },
}

Having a structure like that will let you do this:

store.mountain_bike.price // gives me 10

Need an array instead, say for filtering or looping over?

Object.keys gives you an Array of all the object's keys in the store ['coffee_maker', 'mountain_bike', 'tv']

// Now we just have an array of objects 
// [{id: 'coffee_maker', price: 5}, {id: 'mountain_bike', price: 10} ...etc]
var arr = Object.keys(store).map(el => store[el])

Need to just filter for items that are less than 10?

This will give us an array of products less than 10:

// gives us [{id: 'coffee_maker', price: 5}]
var productsUnder10 = arr.filter(el => el.price < 10)

These techniques can be chained:

var productsOver10 = Object.keys(store)
    .map(el => store[el])
    .filter(el => el.price > 10)

Need to add a product?

store['new_product'] = {
    id: 'new_product',
    description: 'The Newest Product',
    price: 9000,
}

Here's another way, which would be good to start getting used to. This is a 'safe' way to update the store, read up on immutability in javascript to learn about it

store = Object.assign({}, store, {
    'new_product': {
        id: 'new_product',
        description: 'The Newest Product',
        price: 9000,
    }
})

...and another way, that you should also read up on and start using: This is the object spread operator, basically just an easier way to work with immutable structures

store = {
    ...store,
    'new_product': {
        id: 'new_product',
        description: 'The Newest Product',
        price: 9000,
    }
}

Resources

  • JavaScript Arrow Functions
  • Object and Array Spread Syntax
  • Immutable Javascript using ES6 and beyond
like image 123
Jason Awbrey Avatar answered Oct 26 '25 05:10

Jason Awbrey


You can actually use json or create an array of objects.If using a separate file to store the objects, first load the file. Use array filter method to get an new array which matches the filter condition , like you want to get the item with id 1. This will return an array of objects.

var dict = [{
    'id': 1,
    'name': 'coffee-mug',
    'price': 60
  },
  {
    'id': 2,
    'name': 'pen',
    'price': 2
  }
]

function getItemPrice(itemId) {
  var getItem = dict.filter(function(item) {
    return item.id === itemId
  });
  return getItem[0].price;
}

console.log(getItemPrice(1))
like image 36
brk Avatar answered Oct 26 '25 05:10

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!