1

Is it possible to have a key value pair in arrays in javascript. I'm looking to have something like the following

const array = 
[
'item': 'Jumper', 'price', '160',
'item': 'Shirt', 'price', '50',
'item': 'Cap', 'price', '20',
]

Or is there a better datastructure to use?

3
  • What's the point of having key/value pairs where all the keys are same? Commented Jul 30, 2020 at 22:02
  • 1
    If you need key-value pairs, you've to use object. In your case it looks like you'd need an array of objects. Commented Jul 30, 2020 at 22:02
  • 1
    "Better" is hard to determine unless you provide context on what you're trying to accomplish. Do you need O(1) price lookups or are you looking to store a collection primarily for iteration? Commented Jul 30, 2020 at 22:14

2 Answers 2

4

Yes, you just make it an array of objects:

const array = 
[
{'item': 'Jumper', 'price': '160'},
{'item': 'Shirt', 'price': '50'},
{'item': 'Cap', 'price': '20'},
]

console.log(array);

Sign up to request clarification or add additional context in comments.

1 Comment

Good but also consider products = {Jumper: 160, Shirt: 50, Cap: 20} depending on use case; this gives O(1) lookup of price given a name. It's unusual to have numbers represented as strings.
0

Use objects. You can do it the way it's shown in @dave's answer, or you can instead use classes:

class Product {
    constructor(item, price) {
        this.item = item;
        this.price = price;
    }
}

const array = [
    new Product('Jumper', 160),
    new Product('Shirt', 50),
    new Product('Cap', 20),
];

Comments