2

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?

3
  • 1
    Array.prototype.find Commented Jul 9, 2018 at 12:08
  • 1
    If you're doing this often, you'll want to flip the data structure to turn it into {0: 'Unknown', ...} for fast lookup. Commented Jul 9, 2018 at 12:10
  • Possible duplicate of Find object by id in an array of JavaScript objects Commented Jul 9, 2018 at 12:11

3 Answers 3

6

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));

Sign up to request clarification or add additional context in comments.

1 Comment

@Liam If you have ES6, you can use map function.
0

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'])

Comments

0

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 + '"')

.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.