Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing object to array using underscore js or lodash

I have a requirement to parse an object and convert in to an array using Underscore/Lo-Dash

Tried using usersocre, but its not getting expected result. Sorry am new to underscore js. Your help is much appreciated.

var arr = _.values(obj)

var obj = {
    '2c13790be20a06a35da629c71e548afexing': [{
        connector: '',
        displayName: 'John',
        loginName: '',
        userImage: '2.jpg'
    }],
    '493353a4c5f0aa71508d4055483ff979linkedinpage': [{
        connector: '',
        displayName: 'Mak',
        loginName: '',
        userImage: '1.jpg'
    }]
}

expected output array

array = [{
    connector: '2c13790be20a06a35da629c71e548afexing',
    displayName: 'John',
    loginName: '',
    userImage: '2.jpg'
}, {
    connector: '493353a4c5f0aa71508d4055483ff979linkedinpage',
    displayName: 'Mak',
    loginName: '',
    userImage: '1.jpg'
}]
like image 221
Dibish Avatar asked Nov 24 '15 05:11

Dibish


1 Answers

Use Object.keys with forEach and add object in the array.

  1. Get all the keys of the object
  2. Iterate over the keys array using forEach
  3. Push first element of the subarray in the result array.

Code:

var arr = [];
Object.keys(obj).forEach(function(e) {
    // Get the key and assign it to `connector`
    obj[e][0].connector = e;
    arr.push(obj[e][0]);
});

var obj = {
  '2c13790be20a06a35da629c71e548afexing': [{
    connector: '',
    displayName: 'John',
    loginName: '',
    userImage: '2.jpg'
  }],
  '493353a4c5f0aa71508d4055483ff979linkedinpage': [{
    connector: '',
    displayName: 'Mak',
    loginName: '',
    userImage: '1.jpg'
  }]
};

var arr = [];
Object.keys(obj).forEach(function(e) {
  obj[e][0].connector = e;
  arr.push(obj[e][0]);
});

console.log(arr);
document.getElementById('output').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="output"></pre>

The same code be converted to use Lodash/Underscore's forEach.

var arr = [];
_.forEach(obj, function(e, k) {
    e[0].connector = k;
    arr.push(e[0]);
});

var obj = {
  '2c13790be20a06a35da629c71e548afexing': [{
    connector: '',
    displayName: 'John',
    loginName: '',
    userImage: '2.jpg'
  }],
  '493353a4c5f0aa71508d4055483ff979linkedinpage': [{
    connector: '',
    displayName: 'Mak',
    loginName: '',
    userImage: '1.jpg'
  }]
};

var arr = [];

_.forEach(obj, function(e, k) {
  e[0].connector = k;
  arr.push(e[0]);
});

console.log(arr);
document.getElementById('output').innerHTML = JSON.stringify(arr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<pre id="output"></pre>
like image 198
Tushar Avatar answered Oct 06 '22 01:10

Tushar