if name of array object same then combine array object in ts - javascript

I have an array of objects coming from backend.
var values = [
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization ABC",
"value": 3
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization ABC",
"value": 2.5
}
]
},
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization XYZ",
"value": 2.5
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization XYZ",
"value": 3.3
}
]
},
];
I want to combine the inner array's objects and get one single array of objects for same name of objects.
var output = [
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization ABC",
"value": 3
},
{
"name": "Organization XYZ",
"value": 2.5
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization ABC",
"value": 2.5
},
{
"name": "Organization XYZ",
"value": 3.3
}
]
},
];
I think, I need to use reduce but not sure how I can combine objects of series of same name.
Please help and guide. Thanks

You are right with reducer
var values = [
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization ABC",
"value": 3
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization ABC",
"value": 2.5
}
]
},
{
"name": "Patient Introductions",
"series": [
{
"name": "Organization XYZ",
"value": 2.5
}
]
},
{
"name": "Patient Assessment",
"series": [
{
"name": "Organization XYZ",
"value": 3.3
}
]
},
];
var result = values.reduce((acc, curr) => {
var existing = acc.find(element => element.name === curr.name);
if(existing) {
existing.series.push(...curr.series);
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result);

Make a new empty array
loop through your original array if the name does not exist in the
new array then add to it'
if the name existed just add the new array to it
this way ensures no duplicate name will be in the array
var values = [
{
name: "Patient Introductions",
series: [
{
name: "Organization ABC",
value: 3,
},
],
},
{
name: "Patient Assessment",
series: [
{
name: "Organization ABC",
value: 2.5,
},
],
},
{
name: "Patient Introductions",
series: [
{
name: "Organization XYZ",
value: 2.5,
},
],
},
{
name: "Patient Assessment",
series: [
{
name: "Organization XYZ",
value: 3.3,
},
],
},
];
let newValues = [];
values.forEach((value) => {
let index = newValues.findIndex((item) => item.name === value.name);
if (index === -1) {
newValues.push({ name: value.name, series: [value.series[0]] });
} else {
newValues[index].series.push(value.series[0]);
}
});
console.log(newValues)

Related

How to check if an array contains two values with Javascript

I have a JSON object that has an array as below
{
"objects": [
{
"severity": "LOW",
"tags": [
{
"key": "account",
"values": [
"account2"
]
},
{
"key": "accountId",
"values": [
"2"
]
}
],
"name": "object1"
},
{
"severity": "HIGH",
"tags": [
{
"key": "account",
"values": [
"account2"
]
},
{
"key": "accountId",
"values": [
"2"
]
}
],
"name": "object2"
},
{
"severity": "MEDIUM",
"tags": [
{
"key": "account",
"values": [
"account44"
]
},
{
"key": "accountId",
"values": [
"44"
]
}
],
"name": "object2"
},
{
"severity": "HIGH",
"tags": [
{
"key": "account",
"values": [
"account42"
]
},
{
"key": "accountId",
"values": [
"42"
]
}
],
"name": "object2"
}
]
}
I want to be able to go through the array using javascript and if severity is HIGH and acccountID matches 2 for example to set a warning. Even though account 2 might have a severity of LOW as shown, I still want to make the if condition true.
So something like if (objects.some(a =>(a.severity ==="LOW" && ...... or whatever better option there is.
You can loop through your object and match your properties like this
const data = { "objects": [ { "severity": "LOW", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object1" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object2" }, { "severity": "MEDIUM", "tags": [ { "key": "account", "values": [ "account44" ] }, { "key": "accountId", "values": [ "44" ] } ], "name": "object2" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account42" ] }, { "key": "accountId", "values": [ "42" ] } ], "name": "object2" } ] };
// Loop
for(let i = 0; i < data.objects.length; i++) {
// Set severity
const severity = data.objects[i].severity;
// Set ID
let id; for(let ii = 0; ii < data.objects[i].tags.length; ii++) if(data.objects[i].tags[ii].key === 'accountId') id = data.objects[i].tags[ii].values[0];
// Do logic here
if(severity === 'LOW' && id === '2') console.log(data.objects[i]);
}
If you're loop-avert:
if (objects.some(e => e.severity === severity || e.tags.some(t => t.key === 'accountId' && t.values.includes(accountId)))) {
...
For clarity, that closure is:
return e =>
e.severity === severity ||
e.tags.some(t =>
t.key === 'accountId' &&
t.values.includes(accountId));
e.g.
const j = { "objects": [ { "severity": "LOW", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object1" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object2" }, { "severity": "MEDIUM", "tags": [ { "key": "account", "values": [ "account44" ] }, { "key": "accountId", "values": [ "44" ] } ], "name": "object2" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account42" ] }, { "key": "accountId", "values": [ "42" ] } ], "name": "object2" } ] };
function condition(severity, accountId) {
return e =>
e.severity === severity ||
e.tags.some(t =>
t.key === 'accountId' &&
t.values.includes(accountId));
}
if (j.objects.some(condition('LOW', '2'))) {
console.log("warning: low || 2");
}
if (j.objects.some(condition('SUPER_HIGH', '4048'))) {
console.log("warning: super high || 4048");
}

Javascript - Multiple nested filter expressions

Have this JSON object in JavaScript that comes from an API:
[
{
"id": 1,
"label": "Breakfast",
"subCategories": [
{
"id": 100,
"label": "Cereals, Muesli",
"items": [
{
"productId": "4fdddf1d-8d31-411d-a908-5edd68a775b7",
"label": "Bircher Muesli"
},
{
"productId": "000673e7-47ec-4dce-a940-ad4aacbd7d73",
"label": "Individual Cereals"
},
{
"productId": "0f739661-5531-4734-9dfd-e145b60667cc",
"label": "Organic Porridge Oats"
}
]
},
{
"id": 101,
"label": "Eggs, Omelettes",
"items": [
{
"productId": "6d608133-ab44-4f9d-ab8e-fc6a3f955397",
"label": "Crushed Avocado with Soughdough Toast"
},
{
"productId": "fcfe91ab-e9b1-4dc0-8c57-ffb9646e0658",
"label": "Crushed Avocado with Crispy Bacon"
},
{
"productId": "2a80e48b-76f6-4bda-abf3-ec8dc7bf1419",
"label": "Crushed Avocado with Smoked Salmon"
},
{
"productId": "ae35e949-abf3-4795-a5df-9af4250c2185",
"label": "Egg White Omelette"
}
]
}
]
},
{
"id": 2,
"label": "Light Lunch",
"subCategories": [
{
"id": 103,
"label": "Condiments",
"items": [
{
"productId": "25503a9b-b553-4b56-a152-49e4121cf4ae",
"label": "Butter"
},
{
"productId": "c1dd9761-f170-4e6a-a7d7-5519a4213874",
"label": "Jam"
}
]
},
{
"id": 104,
"label": "Yoghurts",
"items": [
{
"productId": "938fed24-6d4c-e0cd-8303-0fcd42c87be4",
"label": "Fruit Yoghurt",
},
{
"productId": "62137176-0966-4424-9093-51bd7871d31b",
"label": "Greek Yoghurt",
},
{
"productId": "307e59c4-b103-43d4-988c-75ee539d5d75",
"label": "Granola Parfait: Layers of Berries, Fruit Granola, Yoghurt & Honey",
}
]
}
]
}
]
I need to filter this array above with the search query (Eg: Greek) against the items.label property and have it returned the filtered outcome like below:
[
{
"id": 2,
"label": "Light Lunch",
"subCategories": [
{
"id": 104,
"label": "Yoghurts",
"items": [
{
"productId": "62137176-0966-4424-9093-51bd7871d31b",
"label": "Greek Yoghurt",
}
]
}
]
}
]
I've tried various implementation with filter() with nested some() as seen on StackOverflow but did not return the desired result. Currently this works but only the top level category is filtered and the nested subcategory only exist if there's a match for item.
var searchQuery="Greek";
var data=[]; //JSON omitted for brevity.
var result = data.filter(a=>{
return a.subCategories.some(b=> {
return b.items.some(c=> new RegExp(searchQuery,"i").test(c.label));
});
});
Any help would be greatly appreciated.
You can use Array.reduce for this, iterating first over each of the categories, then each of the subcategories, only adding the subcategory to the output if one of its items contains the search query, and then only adding the category to the output if one of the subcategories contains the search query:
const data = [{
"id": 1,
"label": "Breakfast",
"subCategories": [{
"id": 100,
"label": "Cereals, Muesli",
"items": [{
"productId": "4fdddf1d-8d31-411d-a908-5edd68a775b7",
"label": "Bircher Muesli"
},
{
"productId": "000673e7-47ec-4dce-a940-ad4aacbd7d73",
"label": "Individual Cereals"
},
{
"productId": "0f739661-5531-4734-9dfd-e145b60667cc",
"label": "Organic Porridge Oats"
}
]
},
{
"id": 101,
"label": "Eggs, Omelettes",
"items": [{
"productId": "6d608133-ab44-4f9d-ab8e-fc6a3f955397",
"label": "Crushed Avocado with Soughdough Toast"
},
{
"productId": "fcfe91ab-e9b1-4dc0-8c57-ffb9646e0658",
"label": "Crushed Avocado with Crispy Bacon"
},
{
"productId": "2a80e48b-76f6-4bda-abf3-ec8dc7bf1419",
"label": "Crushed Avocado with Smoked Salmon"
},
{
"productId": "ae35e949-abf3-4795-a5df-9af4250c2185",
"label": "Egg White Omelette"
}
]
}
]
},
{
"id": 2,
"label": "Light Lunch",
"subCategories": [{
"id": 103,
"label": "Condiments",
"items": [{
"productId": "25503a9b-b553-4b56-a152-49e4121cf4ae",
"label": "Butter"
},
{
"productId": "c1dd9761-f170-4e6a-a7d7-5519a4213874",
"label": "Jam"
}
]
},
{
"id": 104,
"label": "Yoghurts",
"items": [{
"productId": "938fed24-6d4c-e0cd-8303-0fcd42c87be4",
"label": "Fruit Yoghurt",
},
{
"productId": "62137176-0966-4424-9093-51bd7871d31b",
"label": "Greek Yoghurt",
},
{
"productId": "307e59c4-b103-43d4-988c-75ee539d5d75",
"label": "Granola Parfait: Layers of Berries, Fruit Granola, Yoghurt & Honey",
}
]
}
]
}
];
const searchQuery = "Greek";
const regex = new RegExp(searchQuery, "i");
const result = data.reduce((cats, cat) => {
cat.subCategories = cat.subCategories.reduce((subs, sub) => {
sub.items = sub.items.filter(item => regex.test(item.label));
if (sub.items.length) subs.push(sub);
return subs;
}, []);
if (cat.subCategories.length) cats.push(cat);
return cats;
}, []);
console.log(result);
Here I have a working example which returns your requested output:
function finder(data, query) {
for(let i in data) {
// return the item if the label contains the search query
if(new RegExp(query,"i").test(data[i].label)) return data[i]
// go deeper in subCategories if exist
if(data[i].subCategories) {
let sub = finder(data[i].subCategories, query)
if(sub) {
data[i].subCategories = [sub]
return data[i]
}
// go deeper in items if exist
} else if(data[i].items){
let item = finder(data[i].items, query)
if(item) {
data[i].items = [item]
return data[i]
}
}
}
// didn't find the search query in this branch
return false
}
console.log(finder(data, 'Greek'))
with data your input data

How to groupBy in multi arrays using lodash

I want to group By sub-work in array
Here is my array I want to group By sub-work
result = [
{
"date": "10-07-2019",
"data": [
{
"data_id": "20",
"work": "work_1",
"sub-work": "sub_work1",
"sub-data": [
{
"id": 7,
"title": 'subdata-1',
}
]
}
]
},
{
"date": "12-07-2019",
"data": [
{
"data_id": "20",
"work": "work_1",
"sub-work": "sub_work1",
"sub-data": [
{
"id": 7,
"title": 'subdata-1',
}
]
}
]
},
]
Here is what I try
result = _(result)
.map(function(items, data) {
_.groupBy(items.data, function({ sub_work }) {
return sub_work;
});
})
.value();
first I map result into data then I try to groupby but It's return null
Update
I want my output look like this
[
{
"date": "10-07-2019",
sub-work: [{
sub-work : "sub_work1",
sub-data[
{
"id": 7,
"title": 'subdata-1',
}
]
}]
}
]
...........................
It would be better if you could provide your expected result.
Here's what I could infer:
_(result)
.map(function(obj) { // Convert into a 2D array.
return obj.data.map(e => Object.assign(e, {date: obj.date}));
})
.flatten() // We have an array of objects now.
.groupBy('sub-work') // We can call groupBy().
.value();
Here's what you get:
{
"sub_work1": [{
"data_id": "20",
"work": "work_1",
"sub-work": "sub_work1",
"sub-data": [{
"id": 7,
"title": "subdata-1"
}],
"date": "10-07-2019"
}, {
"data_id": "20",
"work": "work_1",
"sub-work": "sub_work1",
"sub-data": [{
"id": 7,
"title": "subdata-1"
}],
"date": "12-07-2019"
}]
}

Creating Array with String and Integers from JSON

Currently I've got the following JSON feed:
var data = {
"feeds": {
"regions": [{
"name": "Lichtenberg",
"id": "01408.b",
"suburbs": [{
"name": "Fennpfuhl",
"views": 76400
},
{
"name": "Lichtenberg",
"views": 87895
},
{
"name": "Rummelsberg",
"views": 10239
}
]
},
{
"name": "Mitte",
"id": "03442.f",
"suburbs": [{
"name": "Tiergarten",
"views": 82695
},
{
"name": "Mitte",
"views": 67234
},
{
"name": "Hansaviertel",
"views": 10848
},
{
"name": "Moabit",
"views": 67500
}
]
},
{
"name": "Friedrichshain-Kreuzberg",
"id": "01991.o",
"suburbs": [{
"name": "Friedrichshain",
"views": "98494"
},
{
"name": "Kreuzberg",
"views": "27800"
}
]
},
{
"name": "Templehof-Schöneberg",
"id": "01778.k",
"suburbs": [{
"name": "Friedenau",
"views": 76595
},
{
"name": "Schöneberg",
"views": 20731
},
{
"name": "Templehof",
"views": 58000
},
{
"name": "Mariendorf",
"views": 32300
}
]
},
{
"name": "Pankow",
"id": "02761.q",
"suburbs": [{
"name": "Wießensee",
"views": 81294
},
{
"name": "Prenzlauer Berg",
"views": 76470
},
{
"name": "Pankow",
"views": 90210
}
]
}
],
}
};
Effectively I want to do two things:
Loop through the Regions to get the 4 names
Loop through all the views in each region, sum them up, and return them as values under the 4 names.
Here's a sample of the output that I just quickly typed up:
var viewsPerRegion =
[{
label: "Litchtenberg",
total: 174534
}, {
label: "Mitte",
total: 228277
}, {
label: "Friedrichshain-Kreuzberg",
total: 126294
}, {
label: "Templehof-Schöneberg",
total: 187626
}];
etc...
I do want to note that data.feeds.region[2].suburbs.views is stored as a string, so that's something I'll need to change into an integer first.
Anyway the solution I have so far (which doesn't really work) is as follows:
var viewsPerRegion, i, j, x;
for (i in data.feeds.regions) {
x += data.feeds.regions[i].name;
for (j in data.feeds.regions[i].suburbs.views){
x += data.feeds.regions[i].suburbs.views[j];
}
}
viewsPerRegion = x;
Any help is certainly appreciated - bit of a newbie in JSON and javascript.
You can map the regions array, extracting the name from each, and get the total by using reduce to add up each of the views:
const data={"feeds":{"regions":[{"name":"Lichtenberg","id":"01408.b","suburbs":[{"name":"Fennpfuhl","views":76400},{"name":"Lichtenberg","views":87895},{"name":"Rummelsberg","views":10239}]},{"name":"Mitte","id":"03442.f","suburbs":[{"name":"Tiergarten","views":82695},{"name":"Mitte","views":67234},{"name":"Hansaviertel","views":10848},{"name":"Moabit","views":67500}]},{"name":"Friedrichshain-Kreuzberg","id":"01991.o","suburbs":[{"name":"Friedrichshain","views":"98494"},{"name":"Kreuzberg","views":"27800"}]},{"name":"Templehof-Schöneberg","id":"01778.k","suburbs":[{"name":"Friedenau","views":76595},{"name":"Schöneberg","views":20731},{"name":"Templehof","views":58000},{"name":"Mariendorf","views":32300}]},{"name":"Pankow","id":"02761.q","suburbs":[{"name":"Wießensee","views":81294},{"name":"Prenzlauer Berg","views":76470},{"name":"Pankow","views":90210}]}],}}
const viewsPerRegion = data.feeds.regions.map(({ name, suburbs }) => ({
label: name,
total: suburbs.reduce((a, { views }) => a + Number(views), 0)
}));
console.log(viewsPerRegion);

get records doing a match between arrays rethinkdb

I want get the id from table records that have the array match with other record from the same table's array example:
it is record of user '1'
✔ r.db('fotogena').table('users').filter({user:'1'}).pluck('pleasures')
{
"pleasures": [
{
"category": "432f1ae0-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1ae1-a7b1-11e7-86dc-d709d79803e4"
]
},
{
"category": "432f1aef-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1af5-a7b1-11e7-86dc-d709d79803e4"
]
},
{
"category": "432f1afa-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1afb-a7b1-11e7-86dc-d709d79803e4",
"432f1afc-a7b1-11e7-86dc-d709d79803e4",
"432f1afd-a7b1-11e7-86dc-d709d79803e4"
]
},
{
"category": "432f1b02-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1b03-a7b1-11e7-86dc-d709d79803e4",
"432f1b04-a7b1-11e7-86dc-d709d79803e4",
"432f1b07-a7b1-11e7-86dc-d709d79803e4"
]
}
]
}
and i want compare each one that items(without the user '1') inside that pleasure.subCategory with others records inside the same table with the same estructure.
Table with 3 records
[
{
"date": "2017-10-03T03:58:02.651Z",
"id": "d82279a7-fbc6-40a2-99ca-39796ea57efa",
"pleasures": [
{
"category": "432f1ae0-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1ae1-a7b1-11e7-86dc-d709d79803e4"
]
},
{
"category": "432f1aef-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1af5-a7b1-11e7-86dc-d709d79803e4"
]
},
{
"category": "432f1afa-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1afb-a7b1-11e7-86dc-d709d79803e4",
]
},
{
"category": "432f1b02-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1b03-a7b1-11e7-86dc-d709d79803e4",
]
}
],
"user": "1"
},
{
"date": "2017-10-07T02:59:45.942Z",
"id": "174c0e35-da79-4ca8-b237-8ec569cc27b1",
"pleasures": [
{
"category": "432f1ae0-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1ae1-a7b1-11e7-86dc-d709d79803e4",
]
},
{
"category": "432f1aef-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1af3-a7b1-11e7-86dc-d709d79803e4",
"432f1af4-a7b1-11e7-86dc-d709d79803e4"
]
},
{
"category": "432f1afa-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1aff-a7b1-11e7-86dc-d709d79803e4",
]
},
{
"category": "432f1b02-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1b04-a7b1-11e7-86dc-d709d79803e4",
]
}
],
"user": "10"
},
{
"date": "2017-10-07T02:07:13.715Z",
"id": "dd11edac-e0f5-43ac-811a-eaa78a6509c7",
"pleasures": [
{
"category": "432f1ae0-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1ae1-a7b1-11e7-86dc-d709d79803e5"
]
},
{
"category": "432f1aef-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1af3-a7b1-11e7-86dc-d709d79803e5"
]
},
{
"category": "432f1afa-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1af3-a7b1-11e7-86dc-d709d79803e6"
]
},
{
"category": "432f1b02-a7b1-11e7-86dc-d709d79803e4",
"subCategory": [
"432f1af3-a7b1-11e7-86dc-d709d79803e7"
]
}
],
"user": "25"
}
]
i think that maybe can be it:
r.db('fotogena').table('users').filter({user:'1'}).pluck('pleasures').map(pleasures=>{
return //do something
})
i could solve it, later of search and search, i could created a script that show that i want get
I had that do in unique query(no joins) compare arrays with arrays using .contains() and worked very good
r.db('fotogena').table('users').filter(users=>{
return users('pleasures').contains(category=>{
return category('subCategory').contains(subCategory=>{
return r.db('fotogena').table('users').filter({user: '1'}).pluck('pleasures').contains(pleasures2=>{
return pleasures2('pleasures').contains(subCate2=>{
return subCate2('subCategory')
.contains(subCategory2=>{
return subCategory2.eq(subCategory)
})
})
})
})
}).and(users('user').ne('1'))
})

Categories

Resources