【问题标题】:how to get the user array only tried everything如何获取用户数组只尝试了一切
【发布时间】:2019-10-04 04:06:58
【问题描述】:

这是我从 node.js 获得的 json 对象

{count: 2, users: Array(2)}
count: 2
users: Array(2)
0: {_id: "5cdd1c260d0b3d0660d85bfc", name: "Punith", email: "puntihdd@gmail.com", request: {…}}
1: {_id: "5cdd1c4d0d0b3d0660d85bfd", name: "Ashwith", email: "ashwith@gmail.com", request: {…}}
length: 2
__proto__: Array(0)
__proto__: Object

我想得到

[
    {
       _id: ,
       name: ,
       email: ,
    }
]

按此顺序

【问题讨论】:

  • 你能显示代码吗?
  • 您目前如何访问它?
  • export const logIn = (email, password) => { console.log('loggin in'); const res = fetch(LOGIN_URL, { method: "POST", headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ email: email, password: password }) }).then(res => res.json()) .catch(err => err); return res; }
  • 您介意把它放在问题的正文中吗?注释不是代码示例的好地方,因为它会丢弃大多数格式...

标签: javascript reactjs http native


【解决方案1】:

嗯,看起来您正在从某个 noSQL 数据库接收对象。 假设您的对象如下所示: {count: 2, users: Array(2)},我们可以通过以下方式获取 users 属性:

const yourObject = { count: 2, users: [{}, {}]};
const users = yourObject.users;

现在我们有了 users 数组,我们可以重新映射它,以便使用 .map() 方法只获得您想要的三个属性(_id、name、email):

//  exactly the same property names like you want:
users.map(x => ({ _id: x._id, name: x.name, email: x.email }));

//  or omitting the underscore on your new items to make it nicer:
users.map(x => ({ id: x._id, name: x.name, email: x.email }));

将这些概念捆绑在一起,下面是一个可能对您有所帮助的工作示例:

const myData = {
    count: 2,
    users: [{
            _id: "5cdd1c260d0b3d0660d85bfc",
            name: "Punith",
            email: "puntihdd@gmail.com",
            request: {
                a: 'value'
            }
        },
        {
            _id: "5cdd1c4d0d0b3d0660d85bfd",
            name: "Ashwith",
            email: "ashwith@gmail.com",
            request: {
                a: 'value'
            }
        }
    ]
}

const users = myData.users;
const formattedUsers = myData.users.map(user => ({
    _id: user._id,
    name: user.name,
    email: user.email
}));

console.log(formattedUsers);

【讨论】:

    【解决方案2】:

    您可以通过map Ajax 请求的响应来提取某些值。但请记住,不能保证对象内部属性的顺序。如果您需要这些属性,您必须返回一个数组,但是您会丢失属性名称信息。相反,可以通过索引 0,1,2 访问这些值。

    const returnUsers = ({users}) => users.map(({_id,name,email}) => ({
         _id,name,email     
       })
    

    或者返回一个数组

    const returnUsers = ({users}) => users.map(({_id,name,email}) => ([
         _id,name,email     
       ])
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多