array of objects in js code example
Example 1: how to get element of an array in javascript
var value = [a,b,c,d];
var value_b = value[1];
Example 2: javascript check if is array
var colors=["red","green","blue"];
if(Array.isArray(colors)){
}
Example 3: list javascript
var fruits = ["Apple", "Banana", "Cherry"];
var books = [];
console.log(fruits[0])
fruits.push("Orange")
fruits[1]="Blueberry"
fruits.splice(0, 1)
fruits.splice(0, 2)
Example 4: javascript array
var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Example 5: array of objects javascript
var widgetTemplats = [
{
name: 'compass',
LocX: 35,
LocY: 312
},
{
name: 'another',
LocX: 52,
LocY: 32
}
]
Example 6: create array of objects javascript
let products = [
{
name: "chair",
inventory: 5,
unit_price: 45.99
},
{
name: "table",
inventory: 10,
unit_price: 123.75
},
{
name: "sofa",
inventory: 2,
unit_price: 399.50
}
];
function listProducts(prods) {
let product_names = [];
for (let i=0; i<prods.length; i+=1) {
product_names.push(prods[i].name);
}
return product_names;
}
console.log(listProducts(products));
function totalValue(prods) {
let inventory_value = 0;
for (let i=0; i<prods.length; i+=1) {
inventory_value += prods[i].inventory * prods[i].unit_price;
}
return inventory_value;
}
console.log(totalValue(products));