JS Object Arrays
JavascriptSetup
Let's say we have a simple object array
let myitems = [
{name:"Apple", type:"Fruit", color:"red", price:2.5},
{name:"Pear", type:"Fruit", color:"green", price:2.3},
{name:"Orange", type:"Fruit", color:"orange", price:1.7},
{name:"Grapes", type:"Fruit", color:"green", price:2.6},
{name:"Banana", type:"Fruit", color:"yellow", price:1.2},
{name:"Peach", type:"Fruit", color:"orange", price:3.7}
];
Find (unique)
We can find a particular object using find
let result = myitems.find(obj => obj.name === "Apple");
This returns:
result = {name:"Apple", type:"Fruit", color:"red", price:2.5}
If nothing is found, it returns undefined
If multiple items match the query, only the first item is returned.
Filter (multiple)
We can find all matched objects using filter
let result = myitems.filter(obj => obj.price >= 2.5);
This returns:
result = [
{name:"Apple", type:"Fruit", color:"red", price:2.5},
{name:"Grapes", type:"Fruit", color:"green", price:2.6},
{name:"Peach", type:"Fruit", color:"orange", price:3.7}
];
If nothing is found, it returns []
Further Info
For more array functions, check out Array Methods