How to transform {2:'b',3:'c',1:'a'} into [{1:'a'},{2:'b'},{3:'c'}] by lodash?
4 Answers
It's fairly trivial using Object.keys + Array.map, you really don't need lodash:
const obj = {2:'b',3:'c',1:'a'};
const arr = Object.keys(obj).map(key => ({ [key]: obj[key] }))
console.log(arr)
Regarding the lack of a sort function, the above code is exploiting the fact that numerically indexed Object keys are (per the spec) stored sequentially. Check the order for yourself:
console.log({2:'b',3:'c',1:'a'})
Here is the relevant portion of the spec
9.1.12 [[OwnPropertyKeys]] ( )
When the [[OwnPropertyKeys]] internal method of O is called the following steps are taken:
Let keys be a new empty List.
For each own property key P of O that is an integer index, in ascending numeric index order
2a. Add P as the last element of keys.
3 Comments
With upcoming Javascript with Object.entries, you could map a new array with single objects.
var data = {2:'b',3:'c',1:'a'},
result = Object
.entries(data)
.sort((a, b) => a[0] - b[0])
.map(([k, v]) => ({ [k]: v }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With lodash, you could use
_.chain,_.toPairs,_.sortBy,_.mapand_.fromPairs
var data = {2:'b',3:'c',1:'a'},
result = _
.chain(data)
.toPairs(data)
.sortBy([0])
.map(o => _.fromPairs([o]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Comments
Lodash is not really necessary to accomplish what you want, but I'm still adding it anyway and add a sorted function. I've also included the native JavaScript way.
const obj = {b: 3, c: 2, a: 1};
const sortByKeys = object => {
const keys = Object.keys(object)
const sortedKeys = _.sortBy(keys)
return _.map(sortedKeys, key => ({ [key]: object[key]}))
}
// the lodash way, and sorted
console.log(sortByKeys(obj))
// simpler way
const result = Object.keys(obj)
.map(key => ({ [key]: obj[key] }))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Comments
Why use lodash? Just use regular Javascript. Solution can be cleaned up a bit but the idea is to loop through your object and push your desired format into a new array. I also throw the sorting in there for convenience, but feel free to re-factor to your liking.
const obj = {2:'b',3:'c',1:'a'}
let newArr = [];
for (var key in obj) {
newArr.push({[key]: obj[key]})
newArr.sort((a, b) => a[key] > b[key])
}
console.log(newArr)