I'm a newbie in Javascript and I'm trying to understand the destructuring approach also with object literals. So what I'm trying to do is to create a function which has two types of arguments: 1. It's a JSON data file which I want to iterate. 2. An object literal with a random value assigned. So I'm trying to iterate with this object value passed as a parameter and filter with the data from the JSON file with an if statement inside the array of objects iterator. And add to arr all the object which match. Thanks everyone in advance.
Array of objects:
[
{ "id": 44, "hours": 100,"finished": false },
{ "id": 22, "hours": 80,"finished": false },
{ "id": 65, "hours": 34,"finished": false },
{ "id": 1098, "hours": 21,"finished": true },
{ "id": 2, "hours": 67,"finished": false },
{ "id": 765, "hours": 32,"finished": false },
{ "id": 223, "hours": 555,"finished": false },
{ "id": 986, "hours": 2,"finished": false }
]
main.js
const data = require('./example.json')
function dataFilter (items, {id: _id, hours: _hours, finished: _finished}) {
for (let i = 0; i < items.length; i++) {
let arr = [];
if (items[i].id === _id) {
arr.push(items[i])
}
else if (items[i].hours >= _hours){
arr.push(items[i])
}
else if (items[i].finished === finished){
arr.push(items[i])
}
return arr;
}
}
console.log(dataFilter(data,{ id: 65 }));
console.log(dataFilter(data,{ hours: 30 }));