DavidMM
DavidMM

Reputation: 187

Javascript array of objects: Best way to return a value?

I have an array of objects in Javascript with two keys with this structure:

"data": [
  {
  "description": "Unknown",
  "type": 0
  },
  {
  "description": "On",
  "type": 1
  },
  {
  "description": "Off",
  "type": 2
  },
  ...
  ]

I want to pass it a 'type' numeric value and if it finds it in the array, returns me the description value. For example, if I pass '0', I want it to return 'Unknown'.

This is easily done with a for or forEach loop, but there is an inbuilt function in JS that lets me do it in a single line?

Upvotes: 2

Views: 102

Answers (3)

Chaitanya Babar
Chaitanya Babar

Reputation: 289

Have a look at the attached code snippet , which gives the desired output.

  • Find function to itreat throughout your array to match the condition i.e in this case the passedIndex to check whether it is present in list

  • If present return the item

var list = [{
    "description": "Unknown",
    "type": 0
  },
  {
    "description": "On",
    "type": 1
  },
  {
    "description": "Off",
    "type": 2
  }
];

function findItem(index) {
  var result = list.find(function(item) {
    if (item.type == index) {
      return item;
    }
  });
  return result.description;
}
var description = findItem(2);
console.log('The Description is "' + description + '"')

.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could use either find

var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }];
  
console.log(data.find(({ type }) => type === 1).description);

or for faster access use a hash table for the types

var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }], 
    types = Object.assign(...data.map(({ type, description }) => ({ [type]: description })));
  
console.log(types[1]);

or a Map

var data = [{ description: "Unknown", type: 0 }, { description: "On", type: 1 }, { description: "Off", type: 2 }], 
    types = data.reduce((m, { type, description }) => m.set(type, description), new Map);
  
console.log(types.get(1));

Upvotes: 6

Manikant Gautam
Manikant Gautam

Reputation: 3581

In one liner you can Filter the list.

var obj=[{
  "description": "Unknown",
  "type": 0
  },
  {
  "description": "On",
  "type": 1
  },
  {
  "description": "Off",
  "type": 2
  }];
  var filterType=1;
  console.log(obj.filter(e=>e.type == filterType)[0]['description'])

Upvotes: 0

Related Questions