4

I have an array of objects like this:

[
{id: 'id1', random: 'labels.prop1'},
{id: 'id2', random: 'labels.prop2'},
{id: 'id3', random: 'texts.anotherprop'}
]

Is there a short way to generate from that array an object based on the property random? I'd need this:

{
  texts: { 
       anotherprop: ''
  },
  labels: { 
       prop1: '', 
       prop2: '' 
  }
}
2
  • Why need the empty values? Commented Feb 6, 2017 at 10:43
  • @ibrahimmahrir I put just there to be clear that those are object properties. Commented Feb 6, 2017 at 10:45

3 Answers 3

1

You can use reduce() two times to build this nested object.

var data = [
{id: 'id1', random: 'labels.prop1'},
{id: 'id2', random: 'labels.prop2'},
{id: 'id3', random: 'texts.anotherprop'}
]

var result = data.reduce(function(r, o) {
  var arr = o.random.split('.')
  arr.reduce(function(a, b, i) {
    return (i != arr.length - 1) ? a[b] || (a[b] = {}) : a[b] = ''
  }, r)
  return r;
}, {})

console.log(result)

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

Comments

1

You could iterate the array and build an object based on the parts of random.

function setValue(object, path, value) {
    var fullPath = path.split('.'),
        way = fullPath.slice(),
        last = way.pop();

    way.reduce(function (r, a) {
        return r[a] = r[a] || {};
    }, object)[last] = value;
}

var data = [{ id: 'id1', random: 'labels.prop1' }, { id: 'id2', random: 'labels.prop2' }, { id: 'id3', random: 'texts.anotherprop' }],
    result = {};

data.forEach(function (o) {
    setValue(result, o.random, '');
});

console.log(result);

Comments

0

var arr = [
  {id: 'id1', random: 'labels.prop1'},
  {id: 'id2', random: 'labels.prop2'},
  {id: 'id3', random: 'texts.anotherprop'}
];

var result = {};
arr.forEach(function(o) {
  var parts = o.random.split('.');
  var r = result;
  var i = 0;
  for( ; i < parts.length - 1; i++) {
    r[parts[i]] = r[parts[i]] || {};
    r = r[parts[i]];
  }
  r[parts[i]] = '';
});

console.log(result);

1 Comment

@ibrahimmahrir I gave you an upvote because it works.

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.