Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I've a logical problem, and I want to solve it with optimised way

This will be accepted value which should be as an array :
Input:

const x = [    
    "name_new",
    "name_test_new",
    "xyz_new",
    "xyz_abc_rest_edit",
]

This is the putout of input, I’m expecting,
Output:

const y = {
    "name":{
      "new":true,
       },
       "name_test":{
      "new":true,
        },
       "xyz":{
    "new":true,
       },
      "xyz_abc_rest":{
    "edit":true,
      },
}

Here Input could be anything similar to a provided array, and the array value should have underscore "_" with data/string input.
and output should be in object format with the provided result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const x = [
  "name_new",
  "name_test_new",
  "xyz_new",
  "xyz_abc_rest_edit",
]

const obj = {}
for (let item of x) {
  const split = item.split('_');
  let key = "";
  for (let i = 0; i < split.length - 1; i++) {
    key += `${split[i]}_`
  }
  obj[key.substring(0, key.length - 1)] = {
    [split[split.length - 1]]: true
  }
}

console.log(obj)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading