Converting a js object into a string map (the opposite from the usual string to object)

349
July 02, 2017, at 6:47 PM

I know there are plenty of methods to take a dot separated string and map it to a js object, and there are hundred of questions with answers on here about that.

But i need to do the reverse:

To convert this:

let object = {
  parts: {
    x: {
      create: () => {
        alert(321);
      },
      update: () => {
        alert(321);
      }
    },
    y: {
      create: () => {
        alert(321);
      },
      update: () => {
        alert(321);
      }
    }
  }
}

To this:

{
  'parts.x.create': () => {
    alert(321);
  },
  'parts.x.update': () => {
    alert(321);
  },
  'parts.y.create': () => {
    alert(321);
  },
  'parts.y.update': () => {
    alert(321);
  }
}

I feel like i am starting to reinvent the wheel when i start to write the code for this. Has anyone else done or seen this before?

Answer 1

This should do the trick:

let object = { 
  parts: { 
    x: { 
      create: () => { 
        alert(321); 
      }, 
      update: () => { 
        alert(321); 
      } 
    }, 
    y: { 
      create: () => { 
        alert(321); 
      }, 
      update: () => { 
        alert(321); 
      } 
    } 
  } 
}; 
 
let convert = (value, keys = '', obj = {}) => { 
  if (typeof value === 'object') { 
    for (let index in value) { 
      convert(value[index], (keys && keys + '.') + index, obj); 
    } 
  } else { 
    obj[keys] = value; 
  } 
  return obj; 
} 
 
let newObject = convert(object); 
console.log(newObject);

Rent Charter Buses Company
READ ALSO
Open a Wordpress PHP redirection in a new tab

Open a Wordpress PHP redirection in a new tab

I am fairly new to web developmentCurrently, I am trying to solve the following problem: I am using Wordpress and the Woocommerce plugin for my website

367
The service is not getting called from my resolve property in route.js

The service is not getting called from my resolve property in route.js

My service which retrieves and processed the data from a web API is not getting called from inside the resolve function in routejs

291
Google API Quota Usage Count

Google API Quota Usage Count

Is there any way to get Google API Quota limits and usage count for give API Key?

379