【问题标题】:How to get data from object in js [duplicate]如何从js中的对象获取数据[重复]
【发布时间】:2021-12-31 19:37:45
【问题描述】:

我有一个对象,想获取 userName

const example = [
  {
    id: 793,
    name: 'John',
    weight: '66',
    data: [
      {
        id: 793,
        userName: 'John Ferny',
      },
    ],
  },
];

我不确定 example.data.filter((item) => item === item.userName 是否正确

【问题讨论】:

  • example[0].data[0].userName.
  • 只有修复语法错误,即缺少括号,代码才能正确。 fixed 代码是否正确 取决于您没有告诉我们的一些事情,例如无论您是否尝试过它并提供所需的结果,或者如果对象发生更改,您通常需要从 example 获得什么。查看链接的帖子并使用ObjectArray 的可用静态和实例方法。

标签: javascript dictionary filter find


【解决方案1】:

直接:

const userName = example[0].data[0].userName;

如果有多个用户名:

const userNames = example.flatMap(({data}) => data.map(({userName})=> userName));

使用 userName === "John Ferny" 查找第一个项目

const item = example.filter(item => item.data.find(({userName}) => userName === user))

const example = [{ id: 793, name: 'John', weight: '66', data: [ { id: 793, userName: 'John Ferny',}, ], },{ id: 794, name: 'Fred', weight: '66', data: [ { id: 794, userName: 'Fred Ferny',}, ], },];

// directly

console.log(example[0].data[0].userName)

// If more than one:

const userNames = example.flatMap(({data}) => data.map(({userName})=> userName))

console.log(userNames)

// To find an object with userName === something

const user = "John Ferny"
const item = example.filter(item => item.data.find(({userName}) => userName === user))
console.log(item)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多