neptune
neptune

Reputation: 1261

Create object from a property in an array of objects

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: '' 
  }
}

Upvotes: 4

Views: 100

Answers (3)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

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);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122047

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)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386600

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);

Upvotes: 1

Related Questions