0

I try to convert some data into a javascript object. The data looks like this:

data = [["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]]

What I want to get is:

a = {
    "a":{
        "a":"value1",
        "b":"value2"
        },
    "b":"value3",
    "c":{
        "a":"value4"
    }
}

Since the amount of nested attributes varies I do not know how to do this transformation.

2
  • You will most likely not get a complete solution for your question. However, I would solve this by using recursion. Pass a portion of the data to a function which processes the first string in the array and passes the rest of the array to itself, until there is only one string left. Commented Feb 2, 2015 at 13:00
  • Yes, actually this is a good idea I should have come up by myself. I'm going to try it. Commented Feb 2, 2015 at 13:21

3 Answers 3

3

This should be the function you're looking for:

function addItemToObject(dict, path){
  if (path.length == 2){
    dict[path[0]] = path[1];
  } else {
    key = path.shift()
    if (! dict[key]) {
      dict[key] = {};
    }
    addItemToObject(dict[key], path);
  }
  return dict;
}

var result = data.reduce(addItemToObject,{});

The function addItemToObject is a recursive function which creates the depth and inserts the value.

This is applied to everything in data using reduce;

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a solution using Ramda.js

const data = [
  ["a","a","a","value1"],
  ["a","a","b","value2"],
  ["a","b","value3"],
  ["a","c","a","value4"]
]

const transformData =
  R.pipe(
    R.map(R.juxt([R.init, R.last])),
    R.reduce(
      (obj, [path, value]) =>
        R.assocPath(path, value, obj),
      {},
    ),
  )

console.log(transformData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Comments

-1

I don't get your desired solution as there are 4 blocks of data but only 3 properties in the final object.

However, this is how you can iterate through an array and its child arrays:

var data = [["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]];

//Store your results in here
var result = {};

//Iterate each block of data in the initial array
data.forEach(function(block){

    //block will refer to an array

    //repeat with the child array
    block.forEach(function(item){
        //item will point to an actual item in the child array
    });

});

forEach() will call a provided function on each item within an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.