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?

2

3 Answers 3

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>

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

Comments

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

1 Comment

I know - I realised that, hence why i deleted the comment 2 seconds later
0

just use _.find shorthand

_.find(empJSON, {id: 'emp123124'})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.