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'
}]
Use Object.keys
with forEach
and add object in the array.
forEach
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With