Grouping with Lodash - javascript

I'm trying to group by "date" an object like this:
let myObj = [
{"date":"01/12","Deposits":50000},
{"date":"01/12","Withdrawals":10000}
]
So if I did groupBy "date", I'd want to receive:
[
{"date":"01/12", "Deposits":50000, "Withdrawals":10000}
]
I tried many different ways without success =(

Here is an approach without lodash, by using .reduce() and the spread syntax ... to extract your wanted properties. By using .reduce() you can group your array's objects into a larger aggregation object (ie: the acc), which you can then get the values() of to get your array of results:
const myObj = [{"date":"01/12","Deposits":50000},{"date":"01/12","Withdrawals":10000}];
const res = Object.values(myObj.reduce((acc, {date, ...rest}) => {
acc[date] = {...(acc[date] || {date}), ...rest};
return acc;
}, {}));
console.log(res);
If you wish to use lodash, here is an approach using _.groupBy(), _.map(), _.assign() and _.flow() which will allow you to make your own function to merge arrays by a key:
const myObj = [{"date":"01/12","Deposits":50000}, {"date":"01/12","Withdrawals":10000}];
const mergeArr = _.flow(
arr => _.groupBy(arr, 'date'),
group => _.map(group, arr => _.assign({}, ...arr))
);
const res = mergeArr(myObj);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

let result = _.map(_.groupBy(myObj, 'date'), value => _.assign(...value));

Related

How to change an array to a JSON format with javascript

I have an array which is in the below format
node=['ADSss|623', 'sss|635']
I want this to be in a json format as below
[
{
"623": "ADSss"
},
{"635": "sss"
}
]
Is there a simple way to achieve this? it is possible with map function, but i felt it is adding up too many lines of code
Assuming that you array only contain string of format ${value}|${key}, you can map those to an object:
const result = node.map((arrayEl) => {
// Split you array string into value and keys
const [value, key] = arrayEl.split('|');
// return an object key: value
return {[key]: value}
});
console.log(result);
In one line :
const node=['ADSss|623', 'sss|635'];
const json = node.reduce((p, n) => ({ ...p, [n.split('|')[1]]: n.split('|')[0] }), {});
const jsonArray = node.map(n => ({ [n.split('|')[1]]: n.split('|')[0] }));
console.log(json);
console.log(jsonArray);

Find the element in json - Using underscore library or other way

I want to find the g:id object in the below given array of objects
If my g:id is like "g:id": "121"
I can find the element like
var item = _.findWhere(obj, {'g:id': '121'});
But what i have is "g:id": ["121"] like an array. How can i find it.
Here's my array of objects.
[
{
"g:id": [
"121"
],
"g:item_group_id": [
"90461"
]
},
{
"g:id": [
"129"
],
"g:item_group_id": [
"90462"
]
}
]
I tried like this var item = _.findWhere(jsonXML, {'g:id'.[0]: '121'}); but it is not valid.
How can i do this by underscore.js or any other way ?
You can use Array.find() with destructuring to get the g:id value from the array:
const arr = [{"g:id":["121"],"g:item_group_id":["90461"]},{"g:id":["129"],"g:item_group_id":["90462"]}]
const result = arr.find(({ 'g:id': [gid] }) => gid === '121')
console.log(result)
Another option is to use Array.includes() to see if the array contains the value (a must if the array may contain more the one value):
const arr = [{"g:id":["121"],"g:item_group_id":["90461"]},{"g:id":["129"],"g:item_group_id":["90462"]}]
const result = arr.find(({ 'g:id': gid }) => gid.includes('121'))
console.log(result)

flatten an array of objects, while also considering for uniqueness

I have the following array of objects.
var array = [
{
name: 'abc',
place1: 'def'
},
{
name: 'abc',
place2: 'ghi'
}]
I am trying to get the following output
var array = [[name:'abc'],[place1:'def'],[place2:'ghi']]
this is my attempt:
let arr = []
array.forEach((element,index) => {
const keys = Object.keys(element)
keys.forEach(e => {
let temp = [];
temp[0] = e;
temp[1] = element[e];
if(!arr.indexOf(temp)
arr.push(temp)
});
});
but I am not getting the expected output.
I'm not sure how a an array of objects with different properties would help you. You should probably use one object with all properties or an array of entries.
However, to get the result you want - merge the array of objects to a single object by spreading into Object.assign() to remove duplicates. Then convert to an array of entries [key, value], and map back to an array of objects:
const array = [{"name":"abc","place1":"def"},{"name":"abc","place2":"ghi"}]
const result = Object.entries(Object.assign({}, ...array))
.map(([k, v]) => ({ [k]: v })) // remove the map to get an array of entries
console.log(result)

How to merge object inside object [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 4 years ago.
I have an array
var input = [["group1","group2","group3" ], ["group1", "group5" ]]
I would like to merge two objects like this :
["group1","group2","group3", "group1", "group5" ]
I tried to merge two objects in one array, however, I couldn't get the answer.
Any help would be appreciated.
I'm not too familiar with js, but can't you concat two arrays with something like
var merged = input[0].concat(input[1]);
You can use concat() like so:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = [].concat.apply([], input);
console.log(output);
Or alternatively, Array.prototype.flat():
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input.flat(1);
console.log(output);
Or if that is "hard" data, and will not change, you could use an even simpler concat() operation:
const input = [
["group1", "group2", "group3"],
["group1", "group5"]
];
const output = input[0].concat(input[1]);
console.log(output);
You can use the concat function to combine the arrays.
const resultArr = [];
input.forEach(curr => {
resultArr.concat(curr);
});
You're talking about 'flattening the array'...
const flatten = (array) => {
return array.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
console.log(flatten([[1,2,[3]],4]));
ES5
array.reduce(function(a, x) { return a.concat(x); }, []);
ES6
array.reduce((a, x) => a.concat(x), []);
There is multiple approaches that you could take, my favorite would be to use the reduce method to transform your bi-dimensional array into one flat array and it would look like this :
function reducer(final_flat_array, inputItem) {
return [...final_flat_array, ...inputItem]
};
let flat_array = input.reduce(reducer, []);
or a more 'imperative' way I guess :
let flat_array = [];
input.forEach(item => flat_array.push(item);

Converting flat array to Id and Name object array using Lodash

let states = ["Georgia","California","FL","TX","MA","NJ"];
How do I convert the states array into Id and Name array collection using lodash.
Is there a way to convert the array in below format ( image shown below):
You don't really need lodash to do that.
let states = ["Georgia","California","FL","TX","MA","NJ"];
let result = states.map((item) => {
return {
id: item,
name: item}})
console.log(result)
You do pretty much the same with lodash
import _ from 'lodash';
result = _.map(states, (item) => {
return {
id: item,
name: item}})
let states = ["Georgia","California","FL","TX","MA","NJ"];
const newObj = [];
_.each(states, state => newObj.push({ id: state, name: state }));
console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_.each performs a function on each item of an Array. With that you can create a new object for each state and push that into a new Array. Note: this could also be accomplished with JavaScript's built in .map.
----- UPDATE -----
Why did I make this complicated many years ago?
const states = ["Georgia","California","FL","TX","MA","NJ"];
const newObj = states.map(state => ({ id: state, name: state }));
console.log(newObj);
No need to use lodash, just map through the array and return a new object for each item in the array.

Categories

Resources