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?
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);
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),
];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.