Generating a new JSON object by extracting URL addresses from an existing JSON and parsing them using JavaScript

I possess a json data file.

      [
  {
  "line": 1,
  "elements": [
    {
      "start_timestamp": "2022-10-17T20:07:41.706Z",
      "steps": [
        {
          "result": {
            "duration": 12216552000,
            "status": "passed"
          },
          "line": 5,
          "name": "m0e",
          "match": {
            "location": "seleniumgluecode.book.user_is_on_homepagee()"
          },
          "keyword": "Given "
        },
        {
          "result": {
            "duration": 2074982200,
            "status": "passed"
          },
          "line": 6,
          "name": "m1e1",
          "match": {
            "location": "seleniumgluecode.book.user_enters_Usernamee()"
          },
          "keyword": "When "
        }
      ],
      "tags": [
        {
          "name": "@Smokee"
        }
      ]
    },
    {
      "start_timestamp": "2022-10-17T20:08:12.284Z",
      "steps": [
        {
          "result": {
            "duration": 12090584100,
            "status": "passed"
          },
          "line": 12,
          "name": "m0e2",
          "match": {
            "location": "seleniumgluecode.book2.user_is_on_homepageee()"
          },
          "keyword": "Given "
        }
      ],
      "tags": [
        {
          "name": "@Smokee"
        }
      ]
    }
  ],
  "name": "Login Featuree",
  "description": "  Verify if user is able to Login in to the sitee",
  "id": "login-featuree",
  "keyword": "Feature",
  "uri": "file:src/test/java/features/tribe/squad1/kitab.feature",
  "tags": []
  },
  {
  "line": 1,
  "elements": [
    {
      "start_timestamp": "2022-10-17T20:08:34.480Z",
      "steps": [
        {
          "result": {
            "duration": 11366098500,
            "status": "passed"
          },
          "line": 5,
          "name": "m0e",
          "match": {
            "location": "seleniumgluecode.book.user_is_on_homepagee()"
          },
          "keyword": "Given "
        }
      ],
      "tags": [
        {
          "name": "@Smokee"
        }
      ]
    }
  ],
  "name": "Login Featureefghfgh",
  "description": "  Verify if user is able to Login in to the sitee",
  "id": "login-featureefghfgh",
  "keyword": "Feature",
  "uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature",
  "tags": []
  },
  {
  "line": 19,
  "elements": [
    {
      "start_timestamp": "2022-10-17T20:09:40.836Z",
      "steps": [
        {
          "result": {
            "duration": 12761711100,
            "status": "passed"
          },
          "line": 23,
          "name": "m0e",
          "match": {
            "location": "seleniumgluecode.book.user_is_on_homepagee()"
          },
          "keyword": "Given "
        }
      ],
      "tags": [
        {
          "name": "@Smokee"
        }
      ]
    }
  ],
  "name": "X Feature",
  "description": "  Verify if user is able to Login in to the sitee",
  "id": "login-featuree",
  "keyword": "Feature",
  "uri": "file:src/test/java/features/tribe2/test.feature",
  "tags": []
  }
  ]

There are URLs present in this array.

    document.addEventListener("DOMContentLoaded", () => {
    var i = report.length;
    var array = [];
    for(x = 0; x < i; x++){
        array.push(report[x].uri.split("/"));

    }
    console.log(array2);
});

Upon execution, I receive:

  0:
  (7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
  1:
  (7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad2', 'kitab2.feature']
  2:
  (6) ['file:src', 'test', 'java', 'features', 'tribe2, kitab3.feature']

The portions file:src, test, java, features are unnecessary and should be removed from all three arrays to create a consolidated unique array like so:

  0:
  (3) ['tribe1', 'squad1', 'kitab.feature']
  1:
  (3) ['tribe1', 'squad2', 'kitab2.feature']
  2:
  (2) ['tribe2, kitab3.feature']

If two elements precede the .feature path, they need to be arranged as squad and tribe respectively. Here's a visual representation:

[tribe1
    squad1
        elem 
             1
             2
        name
        url
    squad2
        elem 
             1
             2
        name
        url
tribe2
    elem 
         1
         2
    name
    url
]

Is there a way to achieve this transformation? Thank you.

Answer №1

Consider using array destructuring for more efficient coding. See the code snippet below:

[x,y,z, ...remaining] = ['apple', 'banana', 'cherry', 'date', 'elderberry']
console.log(remaining);

Answer №2

If you want to manipulate or generate a new array based on an existing input array, you can achieve this using a straightforward approach with the assistance of Array.map() in combination with String.split() and Array.splice() methods.

Here's a demonstration:

const arr = [
  {
    "line": 1,
    "uri": "file:src/test/java/features/tribe/squad1/kitab.feature"
  },
  {
    "line": 1,
    "uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature"
  },
  {
    "line": 19,
    "uri": "file:src/test/java/features/tribe2/test.feature"
  }
];

const res = arr.map(({ uri}) => uri.split('/').splice(4));

console.log(res);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing arrays to store text data in C

After exploring various inquiries, I have made adjustments to my code based on what I have learned. However, my understanding of C seems to be lacking in this scenario, as I am unable to pinpoint the error. Although there are no compilation errors, upon r ...

What is the best way to send multiple responses from an Express server using res.write and execute a specific action after each write operation?

I currently have an active express server that is sending data using res.write() Fetcher.js function fetcher() { console.log("fetcher function called") fetch('/units.html', { method: "POST", body: JSO ...

Fading effect of Bootstrap JS on reducing content size

My quest for a toggle collapse button led me to this helpful link: https://getbootstrap.com/docs/4.0/components/collapse/ I found what I needed, but encountered an issue with the transition; clicking on the button immediately reveals my div. I desire a slo ...

The Vuex store variable is being accessed prior to being populated with information retrieved from the API

I am currently attempting to retrieve data from an API using Vuex. Below is the action function in the Vuex store: async getEpisodeFromApi({ commit }, id) { const data = { id }; return await axios.get(Api.getUrl(data)).then((res ...

Utilize new metadata options to incorporate an external style and script file

I'm looking to incorporate external CSS and scripts into my NextJS app (NextJS version 13.4.13). Here's what I need: Style https://company.com/statics/1/package/dist/1/styles/dls.min.css Script https://company.com/statics/1/package/dist/1/ ...

Using the latitude and longitude data extracted from a MYSQL database using JSON in the Android platform, we can uniquely pinpoint and display markers on

I have retrieved a set of latitude and longitude values from a MYSQL DB in my Android app using JSON (obtained from PHP code). I am able to display these locations on a map successfully. However, I am struggling to figure out how to add markers to these lo ...

What is the best method to deactivate additional choices and add inputs to several dropdown menus containing identical values using angular js?

Would like to have 3 dropdown lists with identical values. The first dropdown must be selected, while the other two are optional. All three dropdowns will have the same options. If a user selects an option in dropdown 1, it will become disabled for the re ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...

Implement an onClick event to the newly created th element using document.createElement()

Through the use of document.createElement("th"), I am dynamically inserting columns into a table. var newTH = document.createElement('th'); Is there a way to add an onClick attribute to this element so that users can delete a column by clicking ...

Setting up the subject line for an email script

I have received an email script from my hosting provider that I need to customize. My goal is to extract the value of radio buttons in a group, and based on their id determine the subject line of the email. If the id is small, the subject should be "föret ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...

Pause and Persist

Can someone help me clarify a code issue I'm facing? I have a piece of code that checks an array for overlapping values based on different criteria. This code specifically deals with rows and columns in a Google Sheet using GAS. Here's what I cur ...

Selecting and allocating various subsets from different sets using numpy

Imagine you have a base array X with the shape of (2, 3, 4), which represents two sets containing 3 elements each, with each element being 4-dimensional. Here is how you can sample from this array in a specific way: For each of the 2 sets, you want to sel ...

I am receiving JSON data on my Android device, but for some reason, it is not parsing correctly. Can anyone help me diagnose the

Here is the JSON format as mentioned in the title: http://prntscr.com/elb4fz. I am uncertain about the parse method functioning correctly since I believe that SearchResults is an array and each result will be displayed as an object. The networkutils code ...

Seeking assistance with iterating through a specific JSON data structure

I am dealing with JSON data that has a specific format: {"errors":{"toDate":["Date error_message"],"name":["name error_message"]}} OR {"success":{"toDate":["Date update_data"],"name":["name update_data"]}} I am looking for a way to loop through this d ...

The icon's transition to text appears to be encountering challenges

I'm having an issue with adding a fade effect to the text on my icons in the navigation bar. I've almost got it working, but it keeps displaying "home" for each icon instead of the correct text. Can anyone help me fix this? Live Example https:// ...

What is the best way to save a user's text input as separate elements in a String[] array

I have a private String[] teamName; and I am trying to store a user input string into it. However, when I try to do this by setting teamName[team] equal to keyboard.nextLine(), I encounter a null exception error. Why is this happening? Here is the code sn ...

Attempting to bundle js files using Browserify, but encountering issues with require('jquery-datetimepicker') not functioning correctly

For bundling my javascript file, I rely on gulp + browserify. I start by running npm install select2 --save require("select2"); module.exports = { init: function() { $('#datetime-start').datetimepicker({ dayOfWeekStart : ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

Strategies for optimizing the storage of data from react-quill to the backend system

My current project involves developing a blogging site using react. I am incorporating the use of react-quill for the text editor functionality, but I'm facing a challenge in determining the most efficient way to store the data generated by this edito ...