0

I've object , I am extracting it key and access it value through extract key . when I give it try it give me error of undefined . I really tried hard but didn't find any solution could someone please help me how to resolve this issue . Thanks

let data = "{\"id\":14133,\"taskType\":\"viewing\",\"propertyId\":479,\"userId\":640,\"subject\":\"Viewing with Arsalan Ahmed at Bahria Town Phase 2\",\"date\":\"2021-02-18T18:44:00.000Z\"}";

  Object.keys(JSON.parse(data)).map(item=>console.log(JSON.parse(data).item,item))

3 Answers3

2

This should work for you :-

You need to access the property using [] brackets syntax like so :-

let data = "{\"id\":14133,\"taskType\":\"viewing\",\"propertyId\":479,\"userId\":640,\"subject\":\"Viewing with Arsalan Ahmed at Bahria Town Phase 2\",\"date\":\"2021-02-18T18:44:00.000Z\"}";

  Object.keys(JSON.parse(data)).map(item=>console.log(JSON.parse(data)[item],item))

But Why ?

Because you're accessing the property item which doesn't exist on data object. Instead the item is a key which can take a value of id, taskType etc and on the basis of it you need a value from the data object.

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
0

Use JSON.parse(data)[item] instead of JSON.parse(data).item and it will work. When you use .item it will treat it as key = "item", instead when you use [item] it will treat it as key = value of item.

Try it below.

let data = "{\"id\":14133,\"taskType\":\"viewing\",\"propertyId\":479,\"userId\":640,\"subject\":\"Viewing with Arsalan Ahmed at Bahria Town Phase 2\",\"date\":\"2021-02-18T18:44:00.000Z\"}";

  Object.keys(JSON.parse(data)).map(item=>console.log(JSON.parse(data)[item],item))
Karan
  • 12,059
  • 3
  • 24
  • 40
0

You are accessing the parsed object by the 'item' property instead of by the variable item. Change .item to [item].

You should also avoid parsing the data twice (executing JSON.parse() twice). Use a variable instead.

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87