Search code examples
javascriptjsonlodash

Lodash: how to create a array with new object structure


Let's say I have an array:

var users = [
  { user: 'barney', age: 36, active: true },
  { user: 'fred',  age: 40, active: false },
  { user: 'travis', age: 37, active: true}
];

I want to create a new array:

var users = [
  {person: {item : { user: 'barney', age: 36, active: true }}},
  {person: {item : { user: 'fred',  age: 40, active: false }}},
  {person: {item : { user: 'travis', age: 37, active: true}}}
];

Obviously, workaround is using for loop to create new array, but I'm using lodash for manipulating my arrays in my project.

Just wonder is there any lodash solution for this.


Solution

  • You could use Array#map for a new structure.

    var users = [{ user: 'barney', age: 36, active: true }, { user: 'fred',  age: 40, active: false }, { user: 'travis', age: 37, active: true}],
        result = users.map(item => ({ person: { item } }));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }