Group Array of Object Nesting Some of the Keys With Specific Names

Group array of object nesting some of the keys with specific names

This can be done with a clever combinartion of _.map and _.groupBy.

const items = [

{

tab: 'Results',

section: '2017',

title: 'Full year Results',

description: 'Something here',

},

{

tab: 'Results',

section: '2017',

title: 'Half year Results',

description: 'Something here',

},

{

tab: 'Reports',

section: 'Marketing',

title: 'First Report',

description: 'Something here',

}

];

function groupAndMap(items, itemKey, childKey, predic){

return _.map(_.groupBy(items,itemKey), (obj,key) => ({

[itemKey]: key,

[childKey]: (predic && predic(obj)) || obj

}));

}

var result = groupAndMap(items,"tab","sections",

arr => groupAndMap(arr,"section", "items"));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Grouping nested arrays data by specific key

Iterate over the array, using Map to store calculated sum.

let data =[ { "id": "05a87dssff-7468-49b1-bae3-0cd06dc22189", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ], }, { "id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ], }, { "id": "06129f89-dd80-49dd-bf5d-a12764c23949", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "Beef burger", "price": 15, "total": "60.00", } ], [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "Beef burger", "price": 15, "total": "60.00", } ], [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ] }];

const map = new Map();

data.forEach(
item => item.details.forEach(
detail => {
const {name, total} = detail[0];
map.has(name) ? map.get(name).total += +total : map.set(name, {name, total: +total})
}
)
);

const result = [...map.values()];

console.log(result);

Group values by a specific key in a nested array

You can reduce a flatted array with the compensated items as follows:

const arr = [  {    id: 123,    compensatedItems: [      {        name: 'Random item 1',        id: '123512',        reason: 'missing_items',      },      {        name: 'Random item 1',        id: '123512',        reason: 'missing_items',      },      {        name: 'Random item 1',        id: '123512',        reason: 'missing_items',      },      {        name: 'Another random item',        id: '24122',        reason: 'missing_items',      },      {        name: 'Another random item',        id: '24122',        reason: 'missing_items',      },    ],  },  {    id: 341,    compensatedItems: [      {        name: 'Random item 1',        id: '123512',        reason: 'missing_items',      },      {        name: 'Random item 1',        id: '123512',        reason: 'missing_items',      },      {        name: 'Another random item',        id: '24122',        reason: 'missing_items',      },    ],  },],
compensatedItems = arr.flatMap(({compensatedItems}) => compensatedItems),
result = Object.values(compensatedItems.reduce((a, {name, ...rest}) => {
(a[name] || (a[name] = {...rest, name, count: 0})).count++;
return a;
}, Object.create(null)));

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

How can I group an array of objects by key?

Timo's answer is how I would do it. Simple _.groupBy, and allow some duplications in the objects in the grouped structure.

However the OP also asked for the duplicate make keys to be removed. If you wanted to go all the way:

var grouped = _.mapValues(_.groupBy(cars, 'make'),
clist => clist.map(car => _.omit(car, 'make')));

console.log(grouped);

Yields:

{ audi:
[ { model: 'r8', year: '2012' },
{ model: 'rs5', year: '2013' } ],
ford:
[ { model: 'mustang', year: '2012' },
{ model: 'fusion', year: '2015' } ],
kia:
[ { model: 'optima', year: '2012' } ]
}

If you wanted to do this using Underscore.js, note that its version of _.mapValues is called _.mapObject.

How to group nested array of objects in js

Loop through each item in the array and see if the vendor email exists as a key already in a dictionary, if it exists push it to that array, otherwise set the value of the vendor email key equal to an array with the current item in it

See code below

const data = [{
_id: "622d70a49bd88b1599026318",
products: [{
_id: "6223186e2278d4e502f5264a",
title: "Product number 1",
price: 600,
cartQuantity: 1,
vendor: {
email: "vendor1@gmail.com"
}
},
{
_id: "622d4e9f9bd88b1599026317",
title: "asdas",
price: 100,
cartQuantity: 5,
vendor: {
email: "vendor2@gmail.com"
}
},
{
_id: "622d4e9f9bd88b1599026317",
title: "asdas",
price: 100,
cartQuantity: 5,
vendor: {
email: "vendor2@gmail.com"
}
}
]
}];

const mapped = {};
data[0].products.forEach(item => {
if (item.vendor.email in mapped) return mapped[item.vendor.email].push(item);

mapped[item.vendor.email] = [item];
});

const expectedFormat = Object.keys(mapped).map(key => {
const o = {};
o[key] = mapped[key];

return o;
});

console.log(expectedFormat)

Iterate nested array items and, upon the same value of a specific key, collect any other entry value as data of a merger which is grouped by key+value

If I'm not missing something, you are looking for this:?

var merged = Array.prototype.concat.apply([], original);

like:

Array.prototype.concat.apply([], [[1,2,3],[4,5], [6]]);
// returns:
// [1, 2, 3, 4, 5, 6]

Another way:

var merged = [];
for(var i = 0; i<original.length; i++) {
for(var j = 0, arr = original[i]; j<arr.length; j++) {
merged.push(arr[j]);
}
}

update:

Yes, I DO HAVE MISSED SOMETHING. Thanks @PeterSeliger for pointing it out. But instead of delete this answer, I'd like to update and correct it.

The code below is NOT TESTED.


function doMergeItems(prev, current) {
// Merge content of "current" with "prev"
// Below is just a simple example, need to be replaced
// according to the desired merging strategy.
if(!prev)
prev = {
classNumber: current.classNumber,
status: [],
terms: [],
};
prev.status.push(current.status);
prev.terms.push(...current.terms);
return prev;
}

var merged = [];
for(var i = 0; i<original.length; i++) {
for(var j = 0, arr = original[i]; j<arr.length; j++) {
var item = arr[j];
var index = merged.findIndex(function(x){
return x.classNumber === item.classNumber;
});
if(index < 0)
merged.push(doMergeItems(null, item));
else
merged[index] = doMergeItems(merged[index], item);
}
}

group by in array using nested array's object field value javascript

You need to return the value of the wanted property.

const
colls = [{ name: "sa", attributes: [{ skin: "green" }, { nose: "good" }] }, { name: "sa", attributes: [{ skin: "red" }, { nose: "bad" }] }, { name: "sa", attributes: [{ skin: "green" }, { nose: "good" }] }, { name: "sa", attributes: [{ nose: "good" }] }],
attributeType = "skin",
groupedCollections = _.groupBy(colls, ({ attributes }) => attributes
.find(attribute => attributeType in attribute)
?.[attributeType]
);

console.log(groupedCollections);
.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>

Group nested array objects to parent key in JQ

You need two nested iterations, one in each array. Save the value of .id in a variable to access it later.

jq -r '
.ticket_fields[] | select(.type=="tagger") | .id as $id
| .custom_field_options[] | [$id, .name, .value]
| @tsv
'

Group array by nested keys

If you just want to group the objects with the same ptj.desc value and don't mind the resulting value being an object with the index for keys, then you can just use R.groupBy like so:

const data = [

{

"name": "ABCD123",

"code": "GFDGF",

"ptj": {

"code": "123",

"desc": "ABCD 123"

}

},

{

"name": "ANGGUN",

"code": "DSFD54",

"ptj": {

"code": "111",

"desc": "111 123"

}

},

{

"name": "GDFDGG",

"code": "HJ2",

"ptj": {

"code": "111",

"desc": "111 123"

}

},

{

"name": "POT",

"code": "POT89",

"ptj": {

"code": "222",

"desc": "222 123"

}

},

{

"name": "POTER UTAMA",

"code": "POTER345",

"ptj": {

"code": "123",

"desc": "ABCD 123"

}

},

{

"name": "ABCD123ABCD",

"code": "LOLL23",

"ptj": {

"code": "123",

"desc": "ABCD 123"

}

},

{

"name": "ANGGUN 2",

"code": "DSFD54",

"ptj": {

"code": "111",

"desc": "111 123"

}

},

{

"name": "GDFDGG",

"code": "HJ2",

"ptj": {

"code": "111",

"desc": "111 123"

}

},

{

"name": "POT",

"code": "POT89",

"ptj": {

"code": "222",

"desc": "222 123"

}

},

{

"name": "POTER UTAMA",

"code": "POTER345",

"ptj": {

"code": "123",

"desc": "ABCD 123"

}

}

]

const fn = R.groupBy(R.path(['ptj','desc']))

console.log(fn(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


Related Topics



Leave a reply



Submit