1

So, I'm struggling to get the data called otherPartyName. This data is fetched from a WebAPI and this is stored in a local state called dataSource. I am using react native and would like to check whether the latest createdBy is equal to otherPartyName. I am able to get the name of createdBy, but am unable to get the value of otherPartyName as I kept getting undefined.

dataSource

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",
  },
]

This is how i get the value of latest createdBy.

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

But whatever I do, I'm getting undefined for otherPartyName

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

if i do console.log(dataSource), I am able to get dataSource shown above as the result, but why am i getting undefined, if i do console.log(dataSource.otherPartyName)

Min UD
  • 99
  • 1
  • 1
  • 12
  • 1
    Looking at your post, I believe dataSource is an array, therefore ```dataSource.otherPartyName``` would not work, but ```dataSource[0].otherPartyName``` should – wakakak Feb 03 '20 at 04:56
  • 1
    When are you accessing `dataSource`? You are more than likely trying to access it before the request has finished getting it. Note you will see `dataSource` as being filled when looking in the console as the request will have finished by that time. See [here](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – Patrick Evans Feb 03 '20 at 04:57

1 Answers1

1

You can get an array of otherPartyName using Array.prototype.map():

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)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46