Home > Mobile >  Get data from an object using string format
Get data from an object using string format

Time:06-22

Is there a way to get object data using string format. For example I have data format like.

{
    "id": "3eef1",
    "name": "Admin",
    "email": "[email protected]",
    "primary_role": {
        "id": "a37ad",
        "name": "Shani",
        "description": " Users",
        "created_at": 1652413392,
        "updated_at": 1652413392
    },
    "created_at": 1652413392,
    "updated_at": 1652413392,
    "roles": [],
    "profile": null,
    "companies": []
}
]

How can I get primary_role in the form of string Like I am doing 'primary_role'.name which is of course a wrong approach.

I have to use it in string format. no loops or looped functions.

CodePudding user response:

First of all you need to store the object in a variable to access it.

const obj = {
    "id": "3eef1",
    "name": "Admin",
    "email": "[email protected]",
    "primary_role": {
        "id": "a37ad",
        "name": "Shani",
        "description": " Users",
        "created_at": 1652413392,
        "updated_at": 1652413392
    },
    "created_at": 1652413392,
    "updated_at": 1652413392,
    "roles": [],
    "profile": null,
    "companies": []
};

Then you can call any of its properties using dot notation like this:

console.log(obj.primary_role.name);

CodePudding user response:

Use npm module jsonpath to get the list for name:

const jp = require("jsonpath")
let source = [{
  "id": "3eef1",
  "name": "Admin",
  "email": "[email protected]",
  "primary_role": {
      "id": "a37ad",
      "name": "Shani",
      "description": " Users",
      "created_at": 1652413392,
      "updated_at": 1652413392
  },
  "created_at": 1652413392,
  "updated_at": 1652413392,
  "roles": [],
  "profile": null,
  "companies": []
}]
let result = jp.query(source, "$[0].primary_role.name")
console.log(result)

// or update your source be a json object
source = {
  "id": "3eef1",
  "name": "Admin",
  "email": "[email protected]",
  "primary_role": {
      "id": "a37ad",
      "name": "Shani",
      "description": " Users",
      "created_at": 1652413392,
      "updated_at": 1652413392
  },
  "created_at": 1652413392,
  "updated_at": 1652413392,
  "roles": [],
  "profile": null,
  "companies": []
}
console.log(source.primary_role.name)
  • Related