I have a object that I am passing through a function. The object is as follows:
items: {
'cannonball': '0',
'cannon stand': '-9000',
'cannon barrel': '800',
.
.
.
}
I have the function filterItem defined like this:
function filterItem(items) {
// console.log(items);
var value = [];
filteredItems = {}
console.log(items);
for (var key in items) {
if (items[key] > 0 && items[key] < 1000) {
value.push(items[key]);
};
};
console.log(value);
};
I am going through the object to filter through items that are between 0 and 1000 in the function. At the end of the function I would like to display the filtered key and value in an object called filteredItems.
How can I implement this to get the following result?
Example output:
filteredItems: {
cannon barrel: '800'
}
Thanks in advance.
If by display, you mean console.log the object, you can make a minor modification to your function:
let items = {
'cannonball': '0',
'cannon stand': '-9000',
'cannon barrel': '800'
};
function filterItems(items) {
filteredItems = {}
for (var key in items) {
if (items[key] > 0 && items[key] < 1000) {
filteredItems[key] = items[key];
};
}
console.log(filteredItems);
};
filterItems(items);
This builds up the filteredItems with the same key => value structure as the original object, and you can work with it in the same way.
Here's the version using Object.entries and Array reduce
var items = {
'cannonball': '0',
'cannon stand': '-9000',
'cannon barrel': '800',
}
function filterItem(items) {
return Object.entries(items).reduce((acc, [key, value]) => {
if (value > 0 && value < 1000) {
acc.push({ [key]: value })
}
return acc;
}, []);
};
console.log(filterItem(items));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With