Converting child arrays into the parent’s attributes and back, in JavaScript.

Lets assume you have a script object that looks basically like:

var parent =  { 
    id: 0, 
    name: 'something', 
    children: [{
            value: true
            key: 'released',
            value: true

This first method takes an object that contains key/value child array, and uses the keys to create new attributes to the parent object, then drops the array.

function formatData(parent){     for (var i; i < parent.children.length; i++) {
         var child = parent.children[i];
         parent[child.key] = child.value;
     delete parent.children; //lets remove memory consumption 

This function reverses the prior function, but also allows you to restrict the fields that you are converting back to an array. So if your parent has an Id field, they don’t lose that.

function deformatData(parent) {
    var children= [];
    for (in task) {
        if (["id", "name", "publisher", "author", "isbn"].findIndex(objMatch) < 0) 
             var child = {
                 key: i,
                 value: parent[i],
             delete parent[i]; 
                      //after creating the details array, lets reduce the bandwidth and memory.
     parent.children = children; 

This is the function that the Array.prototype.findIndex is using above.

function objMatch(obj, index, objArray) {
    return obj === objArray(index);

And there you have it. A format and de-format of javascript objects.

The other option is to create functions for each of the elements in the array, and have the function return the corresponding array value.

Your functions would look something like

parent[i] = function(newVal){ 
    if (newVal === undefined){
        return parent.child[0].value }
    else {
        parent.child[0].value = newVal

You can probably guess which one I would rather work with.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.