0

I have a JSON string as follows:

var empJSON = {
    "Emp1":{
        id:"emp123124",
        name:"xyz"
    },
    "Emp2":{
        id:"emp12654",
        name:"abx"
    }
};

The structure of JSON is fixed.

I want to fetch the current object which has a specific id.

e.g. The Emp1 object where id is "emp123124".

How can I do this easily using lodash?

Terry Young
  • 3,531
  • 1
  • 20
  • 21
Hopp
  • 153
  • 1
  • 1
  • 7
  • 1
    That's not JSON but a plain old object: [What is the difference between JSON and Object Literal Notation?](http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jan 12 '17 at 10:56
  • What have you tried? Please, can you show us [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – Andrea Jan 12 '17 at 10:57

3 Answers3

2

_.find()

Iterates over elements of collection, returning the first element predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).


var empJSON = {
  "Emp1": {
    id: "emp123124",
    name: "xyz"
  },
  "Emp2": {
    id: "emp12654",
    name: "abx"
  }
};

var id = "emp12654";
var result = _.find(empJSON, function(emp) { return emp.id === id });

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Andreas
  • 21,535
  • 7
  • 47
  • 56
0

Use native JavaScript Object.keys and Array#find methods.

var empJSON = {
  "Emp1": {
    id: "emp123124",
    name: "xyz"
  },
  "Emp2": {
    id: "emp12654",
    name: "abx"
  }
};

var id = 'emp12654';
 
var res = empJSON[Object.keys(empJSON).find(function(k) {
  return empJSON[k].id == id;
})];

console.log(res);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

just use _.find shorthand

_.find(empJSON, {id: 'emp123124'})
stasovlas
  • 7,136
  • 2
  • 28
  • 29