Note that there are some explanatory texts on larger screens.

plurals
  1. POAny standard JavaScript library for transforming JS objects
    primarykey
    data
    text
    <p>I have a complex nested JavaScript object with me. The requirement is to flatten out the object completely or only some of the members in it.</p> <pre><code>var obj = { a: { b: { c: { d: "Varun" }, e: "kumar" } } }; </code></pre> <p>The expected resultant object:</p> <pre><code>{d: "Varun", e: "kumar"} </code></pre> <p>I have written a simple transform utility which will accept the accessor map in the form {"a.b.c.d": "d"} and transform the object into the new object. I am not supporting arrays for now. Also, the transform utility can only reduce a complex object into a simpler one and not vice-versa (ie. construct a new member object from a simple member). </p> <pre><code>"use strict"; var ObjectUtil = (function () { // constructor var cls = function () { }; // public static cls.getValueFromAccessor = function (obj, accessor) { if (obj == null || accessor == null) return null; return accessor.split(".").reduce(function(prev, current, index) { var reducedObject = prev; if (index == 1) reducedObject = obj[prev]; if (reducedObject == null) return null; return reducedObject[current]; }); }; cls.transform = function(obj, accessorMap, overlay) { var result; if (overlay) result = obj; else result = {}; for (var k in accessorMap) { result[accessorMap[k]] = cls.getValueFromAccessor(obj, k); } return result; }; return cls; })(); var obj = { a: { b: { c: { d: "Varun" }, e: "kumar" } } }; var accessorMap = { "a.b.c.d": "d", "a.b.e": "e" } ObjectUtil.getValueFromAccessor(obj, "a.b.c.d"); console.log(ObjectUtil.transform(obj, accessorMap, false)); console.log(ObjectUtil.transform(obj, accessorMap, true)); </code></pre> <p>Is there a standard way of transforming objects from one form to another. Any libraries available for this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload