从对象返回未定义的值

时间:2020-02-03 04:52:29

标签: javascript reactjs react-native

因此,我正在努力获取名为otherPartyName的数据。这些数据是从WebAPI获取的,并存储在称为dataSource的本地状态中。我正在使用本机反应,想检查最新的createdBy是否等于otherPartyName。我可以获取createdBy的名称,但是由于不断获取undefined,所以无法获取otherPartyName的值。

数据源

Array [
  Object {
    "comment": "Min vintage",
    "feedbackId": 32,
    "otherPartyName": "DooDooDooDooDoo",
    "replies": Array [
      Object {
        "comments": "Bruh ",
        "createdBy": "Min Cunt",
        "feedbackLogId": 32,
        "feedbackReplyLogId": 4,
      },
      Object {
        "comments": "So this is 1",
        "createdBy": "Min Cunt",
        "feedbackLogId": 32,
        "feedbackReplyLogId": 5,
      },
    ],
    "sender": "43434343",
    "type": "Improvement",
  },
]

这就是我获取最新createdBy的值的方式。

let totalCount = dataSource.reduce((a, c) => a + c.replies.length, 0);
let reply = dataSource.map(({ replies }) => replies[totalCount - 1].createdBy)

但是无论我做什么,我都无法为otherPartyName定义

let otherParty = dataSource.otherPartyName
let otherParty = dataSource[0].otherPartyName
let otherParty = dataSource.map(({ otherParty }) => otherParty.otherPartyName)

如果我做console.log(dataSource),我可以得到上面显示的 dataSource ,但是如果我做console.log(dataSource.otherPartyName)

,为什么我变得未定义

1 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.map()获得otherPartyName的数组:

const dataSource = [{ "comment": "Min vintage", "feedbackId": 32, "otherPartyName": "DooDooDooDooDoo", "replies": [{ "comments": "Bruh ", "createdBy": "Min Cunt", "feedbackLogId": 32, "feedbackReplyLogId": 4, }, { "comments": "So this is 1", "createdBy": "Min Cunt", "feedbackLogId": 32, "feedbackReplyLogId": 5, }], "sender": "43434343", "type": "Improvement", }]
const otherPartyNames = dataSource.map(ds => ds.otherPartyName)

console.log(otherPartyNames)