0

So I want to get the object by the id 1 in this object:

let users = {
  'users': {
    'user1': {
      'id': '1',
      'name': 'Brandon',
      'DOB': '05/04/2000'
    },
    'user2': {
      'id': '2',
      'name': 'Jefferson',
      'DOB': '05/19/2004'
    }
  }
}

and I want it to return the entire 'user1' array and log it, does anyone know how I could do this?

I looked all over stackoverflow, and docs, and couldn't find a way to do this. Could I get some help?

bu1d3r
  • 21
  • 1
  • 2
  • 4
  • Did you looked for `Object.entries` and `find` ? – Code Maniac Sep 15 '19 at 16:34
  • Possible duplicate of [How to deep filter objects (not object arrays)](https://stackoverflow.com/questions/50012040/how-to-deep-filter-objects-not-object-arrays) – shkaper Sep 15 '19 at 16:44

6 Answers6

1

There are a few approaches, both of these should roughly achieve what you're looking for:

let users = {
  'users': {
    'user1': {
      'id': '1',
      'name': 'Brandon',
      'DOB': '05/04/2000'
    },
    'user2': {
      'id': '2',
      'name': 'Jefferson',
      'DOB': '05/19/2004'
    }
  }
}

const findUserById = (id) => {
  const key = Object.keys(users.users).find(user => users.users[user].id === '1')
  return users.users[key]
}

console.log(findUserById('1'))

let users = {
  'users': {
    'user1': {
      'id': '1',
      'name': 'Brandon',
      'DOB': '05/04/2000'
    },
    'user2': {
      'id': '2',
      'name': 'Jefferson',
      'DOB': '05/19/2004'
    }
  }
}

const findUserById = (id) => {
  const [key, user] = Object.entries(users.users).find(([key, user]) => user.id === '1');
  return user;
}

console.log(findUserById('1'))
skovy
  • 5,430
  • 2
  • 20
  • 34
1

While the answer by skovy is right and this is what you should be doing in an actual production setting, I would advise against applying it immediately in your situation.

Why? Your question shows that you first need to learn some basic principles any JavaScript programmer should have, that is:

How to iterate over contents of an object

The simplest method used to iterate over an object's keys is the for .. in loop. When iterating over an object's keys using the for .. in loop, the code inside the curly brackets will be executed once for every key of the object we are iterating.

let users = {
   "user1": {
       "id": 1
   },
   "user2": {
       "id": 2
   }
}
for (let key in users) {
    console.log(key);
}

The above code will print:

user1
user2

Proceeding from that, it should be clear how to find the element we want:

let foundUser = null;
for (let key in users) {
    if (users[key].id === 1) {
        foundUser = users[key];
        break;
    }
}
// now found user is our user with id === 1 or null, if there was no such user

When not to do that

If you have a complex object which is a descendant of another object and don't want to iterate over inherited properties, you could instead get an array of current object's keys with Object.keys:

let users = {
   "user1": {
       "id": 1
   },
   "user2": {
       "id": 2
   }
}
const keys = Object.keys(users) // now this is an array containing just keys ['user1', 'user2'];
let foundUser = null;
// now you can iterate over the `keys` array using any method you like, e.g. normal for:
for (let i = 0; i < keys.length; i++) {
    if (users[keys[i]].id === 1) {
        foundUser = users[keys[i]];
        break;
    }
}
// or alternatively `for of`:
for (for key of keys) {
    if (users[key].id === 1) {
        foundUser = users[key];
        break;
    }
}

Other options

You could use Object.values to get an array containing all values of the object:

let users = {
   "user1": {
       "id": 1
   },
   "user2": {
       "id": 2
   }
}
const values = Object.values(users); // values: [{"id":1},{"id":2}]

You can now find the entry you want on your own:

let foundUser = null
for (let i = 0; i < values.length; i++) {
    if (values[i].id === 1) {
        foundUser = values[i];
        break;
    }
}

Or using the Array's find method:

let foundUser = values.find(user => user.id === 1);
// now foundUser contains the user with id === 1

Or, shorter and complete version:

let users = {
   "user1": {
       "id": 1
   },
   "user2": {
       "id": 2
   }
}
const foundUser = Object.values(users).find(user => user.id === 1);
// now foundUser is `{ id: 1 }`
Andrei Chernikov
  • 360
  • 1
  • 2
  • 12
  • Hi Andrei, hope you could help me with my doubt. i have a json and still i couldn't grab my head how to parse it in js/node js – surya kiran Apr 27 '21 at 08:09
  • https://stackoverflow.com/questions/57946100/how-could-i-find-a-json-object-by-id-using-nodejs-js .! here i have posted the problem of mine – surya kiran Apr 27 '21 at 08:43
  • @suryakiran you parse the json string with `JSON.parse(jsonString)`, it returns json object. And your link points to this question, not to yours. – Andrei Chernikov Apr 28 '21 at 00:59
1

Not a big fan of reinventing the wheel. We use object-scan for most of our data processing now. It's very handy when you can just use a tool for that kind of stuff. Just takes a moment to wrap your head around how to use it. Here is how it could answer your questions:

// const objectScan = require('object-scan');

const find = (id, data) => objectScan(['**.id'], {
  abort: true,
  rtn: 'parent',
  filterFn: ({ value }) => value === id
})(data);

const users = { users: { user1: { id: '1', name: 'Brandon', DOB: '05/04/2000' }, user2: { id: '2', name: 'Jefferson', DOB: '05/19/2004' } } };

console.log(find('1', users));
// => { id: '1', name: 'Brandon', DOB: '05/04/2000' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I'm the author of object-scan

vincent
  • 1,953
  • 3
  • 18
  • 24
0

A simple for loop would do it:

let users = {
    'users': {
      'user1': {
        'id': '1',
        'name': 'Brandon',
        'DOB': '05/04/2000'
      },
      'user2': {
        'id': '2',
        'name': 'Jefferson',
        'DOB': '05/19/2004'
      }
    }
  }
let desiredUser = {};
Object.keys(users.users).forEach((oneUser) => {
    if(users.users[oneUser].id === "1")
        desiredUser = users.users[oneUser];
    
});   

console.log(desiredUser);
Nicolas El Khoury
  • 5,867
  • 4
  • 18
  • 28
0

You can also use reduce for this... as well as if you wanted to return the "entire" object, you could do:

let USER_LIST = {
  'users': {
    'user1': {
      'id': '1',
      'name': 'Brandon',
      'DOB': '05/04/2000'
    },
    'user2': {
      'id': '2',
      'name': 'Jefferson',
      'DOB': '05/19/2004'
    }
  }
}

function findUserById(id){
  return Object.entries(USER_LIST.users).reduce((a, [user, userData]) => {
    userData.id == id ? a[user] = userData : '';
    return a;
  }, {});
}

console.log(findUserById(1));
Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41
0

I agree with the Answers. just a short and simple way is to use .find() method

 //--data returned-----//
 data = [{"Id":22,"Title":"Developer"},{"Id":45,"Title":"Admin"}]


      fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            console.log(obj);
            var foundItem = obj.find(o=>o.Id==id);
            console.log(foundItem);
       });
MJ X
  • 8,506
  • 12
  • 74
  • 99