Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain Key from value javascript

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.

like image 991
Nick Avatar asked Jan 26 '26 11:01

Nick


2 Answers

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.

like image 88
bmartin Avatar answered Jan 28 '26 01:01

bmartin


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));
like image 39
Rikin Avatar answered Jan 28 '26 00:01

Rikin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!