简体   繁体   English

我如何使用 nodejs/js 通过 id 找到一个 json 对象

[英]How could I find a json object by id using nodejs/js

So I want to get the object by the id 1 in this object:所以我想通过这个对象中的 id 1 来获取对象:

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?我希望它返回整个“user1”数组并记录它,有谁知道我该怎么做?

I looked all over stackoverflow, and docs, and couldn't find a way to do this.我查看了stackoverflow和文档,但找不到办法做到这一点。 Could I get some help?我能得到一些帮助吗?

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

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.虽然 skovy 的答案是正确的,这就是您在实际生产环境中应该做的事情,但我建议不要在您的情况下立即应用它。

Why?为什么? Your question shows that you first need to learn some basic principles any JavaScript programmer should have, that is:您的问题表明您首先需要学习任何 JavaScript 程序员都应该具备的一些基本原则,即:

How to iterate over contents of an object如何遍历对象的内容

The simplest method used to iterate over an object's keys is the for .. in loop.用于迭代对象键的最简单方法是for .. in循环。 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.当使用for .. in循环迭代对象的键时,大括号内的代码将对我们正在迭代的对象的每个键执行一次。

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 :如果您有一个复杂对象,它是另一个对象的后代,并且不想迭代继承的属性,则可以使用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:您可以使用Object.values来获取包含对象所有值的数组:

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 :或者使用数组的find 方法

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 }`

A simple for loop would do it:一个简单的 for 循环就可以做到:

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

You can also use reduce for this... as well as if you wanted to return the "entire" object, you could do:您也可以为此使用reduce ......以及如果您想返回“整个”对象,您可以这样做:

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

I agree with the Answers.我同意答案。 just a short and simple way is to use .find() method只是一个简短的方法是使用 .find() 方法

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

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免责声明:我是对象扫描的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM