Create a variety of URL formats for various object cases

Can you guide me on how to verify and create a URL under different circumstances?

I am dealing with 3 cases that involve different types of objects:

"repositories": {
  "toto": {
    "tata": "https://google.com/",
    "titi": "images"  
 }
},

The second case is as follows:

"repositories": {
"toto": {
  "tata": "https://google.com/",
  "titi": ""  // empty string
 }
},

And the third case like this:

"repositories": {
"toto": {
  "tata": "https://google.com/",
   // no "titi" key
 }
},

I need assistance in generating a URL while considering these 3 distinct scenarios.

I'm unsure how to handle the 2nd and 3rd cases within the same script.

In my current script, I have:

else if (type === "toto") {
        const totoURi = repositories.toto.tata;
        const titi = repositories.toto.titi; 
        // Struggling to incorporate the logic for the 2nd and 3rd cases

        const url =
            totoURi +
            titi +
            "." +
            type;
       // Example for first case: https://google.com/images.toto
       // Expected for 2nd case: https://google.com.toto
       // Expected for 3rd case: https://google.com.toto
}

Thank you for any guidance or help provided.

Answer №1

Here is an example demonstrating the usage of the Nullish coalescing operator

const createUrl = repo => {
  const url = new URL(repo.toto.tata);
  url.pathname = repo.toto.titi ?? "";
  return url;
}

const repositories1 = { "toto": { "tata": "https://google.com/", "titi":  "images" } }
const repositories2 =  {"toto": {"tata": "https://google.com/", "titi": "" }}
const repositories3 =  { "toto": { "tata": "https://google.com/" } }

console.log(createUrl(repositories1))
console.log(createUrl(repositories2))
console.log(createUrl(repositories3))

For compatibility with older browsers

const makeUrl = rep => {
  const url = new URL(rep.toto.tata);
  url.pathname = rep.toto.titi ? rep.toto.titi : "";
  return url;
}

const repositories1 = { "toto": { "tata": "https://google.com/", "titi":  "images" } }
const repositories2 =  {"toto": {"tata": "https://google.com/", "titi": ""}}
const repositories3 =  { "toto": { "tata": "https://google.com/" }}

console.log(makeUrl(repositories1))
console.log(makeUrl(repositories2))
console.log(makeUrl(repositories3))

Answer №2

let data0 = {
    repositories: {
      toto: {
        tata: "https://tata/",
        titi: "titi"
      }
    }
  },
  data1 = {
    repositories: {
      toto: {
        tata: "https://tata/",
        titi: ""
      }
    }
  },
  data2 = {
    repositories: {
      toto: {
        tata: "https://tata/"
      }
    }
  };

function generateUrls(data) {
  
  const keys = data.repositories.toto;
  let url = "";
  Object.values(keys).forEach((val) => (url += val));
  return url;
}

console.log(generateUrls(data0));
console.log(generateUrls(data1));
console.log(generateUrls(data2));

Answer №3

Make sure to include a nullish check in your code

const obj1 =  {
  "tata": "https://google.com/",
  "titi": "images"
};

const obj2 =  {
  "tata": "https://google.com/",
  "titi": ""
};

const obj3 =  {
  "tata": "https://google.com/",
};

function verifyNotNull(obj) {
  if (obj.titi === null || obj.titi === undefined) return "case 3"
  if (!obj.titi) return "case 2"
  return "case 1"
}

console.log(verifyNotNull(obj1));
console.log(verifyNotNull(obj2));
console.log(verifyNotNull(obj3));

Answer №4

By including the .toto mentioned in your question, the following results are obtained:

const example1 = {
  "repositories": {
    "toto": {
      "tata": "https://google.com",
      "titi": "images"
    }
  }
};

const example2 = {
  "repositories": {
    "toto": {
      "tata": "https://google.com",
      "titi": "" // empty string
    }
  }
};

const example3 = {
  "repositories": {
    "toto": {
      "tata": "https://google.com",
      // no titi key provided
    }
  }
};

const generateUrl = caseNum => {
  const url = new URL(caseNum.repositories.toto.tata)
  url.pathname = caseNum.repositories.toto.titi ? caseNum.repositories.toto.titi : "";
  let urlString = url.toString();
  if (urlString.charAt(urlString.length - 1) == '/') {
    urlString = urlString.slice(0, -1);
  }
  return `${urlString}.toto`;
}

console.log(generateUrl(example1));
console.log(generateUrl(example2));
console.log(generateUrl(example3));

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

Working with Angular: Accessing SCSS variables from style.scss using JavaScript inside a component

I am working on an Angular 9 application that utilizes Angular Material and has two themes, namely dark and light. These themes are defined in the style.scss file as follows: $rasd-dark-text-color: mat-palette($mat-grey, 300); $rasd-light-text-color: mat-p ...

In TypeScript, if all the keys in an interface are optional, then not reporting an error when an unexpected field is provided

Why doesn't TypeScript report an error when an unexpected field is provided in an interface where all keys are optional? Here is the code snippet: // This is an interface which all the key is optional interface AxiosRequestConfig { url?: string; m ...

What are the best circumstances for applying JavaScript in ASP.NET?

As someone who is just starting out in ASP.Net, I have been exploring Validation Controls. However, I am curious about the specific scenarios in which JavaScript would be more appropriate to use. Can anyone provide insight on this? ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

Error Message: Undefined Service in Angular version 1.5.4

I'm currently developing a sample application using AngularJS 1.5.4, built on angular seed, EcmaScript 6, and with a node.js web server. For routing, I am following the guidelines provided here: https://docs.angularjs.org/guide/component-router. Howe ...

Clicking on a radio button can trigger the selection of another radio button

I'm currently working on a form that includes 8 radio buttons - 4 for System A and 4 for System B. The options for the buttons are CF, ISO, ISO-B, and NW. My goal is to create a functionality where selecting a radio button in System A automatically se ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

Why is this tetris piece not appearing fully on the grid when using arrays?

Below is the code snippet, and you can find a link to the jsfiddle below. I'm facing an issue where the first row of the block is not being drawn, and dealing with these 2-dimensional loops is quite challenging for me. I am unable to figure out why t ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...

Automatically fill in form fields with data from a JSON file as soon as the user enters a value

How can I retrieve the bank name, branch, city, and district from a JSON array? Below is the contents of my results.json file: { "ifsc": [{ "ifsc": "PUNB0000100", "bank": "PUNJAB NATIONAL BANK", "city": "ABOHAR ...

Javascript is coming back with a message of "Access-Control-Allow-Origin" not being allowed

I've been encountering some unusual challenges with my React application related to the Access-Control-Allow-Origin issue. Initially, I had similar issues with the login and registration system which I thought were resolved, but now I'm facing di ...

Is it possible to design a collapsible element that gives a sneak peek of its content before fully expanding?

In the title, I mentioned that I require the collapsible to display its content partially before expanding and then fully after expanding. To illustrate this concept, here are two drawings for reference: https://i.sstatic.net/f4CHh.png https://i.sstatic. ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

Harnessing Spread Syntax with Map and Filter Operations

Recently stumbled upon a fascinating problem that I couldn't wait to share with all of you. Here is the question at hand: [...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7] I managed to successfully solve the initial section up to the fi ...

What is the method for retrieving the title element from the Json data?

I am attempting to extract JSON data from http://omadbapi.com/?s= for a search script, but I am encountering difficulties in retrieving the Title element from this particular JSON: { "Search": [{ "Title": "Sherlock Holmes: A Game of Shadows", ...

Having trouble fetching results from AJAX objects using vanilla JavaScript?

I am currently working on developing my own AJAX prototype without relying on jQuery or any other libraries. However, I am facing an issue where I cannot retrieve any results and the breakpoint set on a specific line is not triggering: The problem seems t ...

NodeJS JSONStream causing memory exhaustion issue

I've encountered an issue while trying to stream a large JSON file (94mb in size) from an HTTP request to a local file using the JSONStream library in NodeJS. Despite setting a memory flag of 256mb with node --max-old-space-size=256 .\main.js, th ...

Guide to importing OBJ file into three.js using TypeScript

Currently, I am utilizing TypeScript along with three.d.ts obtained from definitely typed. While I have successfully been using THREE.JSONLoader, I am encountering difficulties with implementing an OBJLoader from here in a TypeScript project. It seems th ...