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);
Related
Trying to get my head around this one..
Incoming data looks like:
[
{
"value": {
"label": "MZ Algal bloom",
"type": "case",
"incident": {
"name": "Algal bloom"
},
"personName": "Lionel Carter"
}
},
{
"value": {
"label": "BW Algal bloom",
"type": "case",
"incident": {
"name": "Algal bloom"
},
"personName": "Jerome Yost"
}
},
{
"value": {
"label": "Detergent",
"type": "case",
"incident": null,
"personName": "Jerald Legros"
}
}
]
I would like to transform this into
[
{
"label": "Algal bloom",
"children": [
{ "label": "Lionel Carter", "type": "case"},
{ "label": "Jerome Yost", "type": "case" }]
},
{ "label": "Detergent", "type": "case" }
]
Basically, the rule is that if incident is not NULL then the incident name becomes the parent and the children hold the personName - otherwise we simply pass through the label and type. I can walk the array and switch out the label with the incident name, but I'm not sure how to group up the incidents..
It's basic grouping with an exception for elements without incident.
You can group the elements without incident in a separate group:
const data = [{"value": {"label": "MZ Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Lionel Carter"}},{"value": {"label": "BW Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Jerome Yost"}},{"value": {"label": "Detergent","type": "case","incident": null,"personName": "Jerald Legros"}}];
function group(data) {
const result = data.reduce((acc, { value }) => {
if (!value.incident) {
acc.ungrouped.push({ label: value.label, type: value.type });
} else {
if (!acc.groups[value.incident.name]) acc.groups[value.incident.name] = { label: value.incident.name, children: [] };
acc.groups[value.incident.name].children.push({ label: value.personName, type: value.type });
}
return acc;
}, { groups: {}, ungrouped: [] });
return [...Object.values(result.groups), ...result.ungrouped];
}
console.log(group(data));
I have a huge json which I am fetching from Excel sheet.
Data I am getting as array of objects and one object looks like below.
[
{
"key": "guid",
"parent": "id__guid"
},
{
"key": "version",
"parent": "id__version"
},
{
"key": "register",
"parent": "register"
},
{
"key": "offloadId",
"parent": "offloadId"
},
{
"key": "action",
"parent": "action"
},
{
"key": "reported",
"parent": "reported"
},
{
"key": "control",
"parent": "control"
},
{
"key": "AppNum",
"parent": "Identification__AppNum"
},
{
"key": "DataTp",
"parent": "Identification__DataTp"
},
{
"key": "DtOgWatchDt",
"parent": "Identification__DtOgWatchDt"
},
{
"key": "DtPendingWatchDt",
"parent": "Identification__DtPendingWatchDt"
},
{
"key": "IssRef",
"parent": "Identification__IssRef"
},
{
"key": "ImgRef",
"parent": "Identification__ImgRef"
},
{
"key": "Register",
"parent": "Identification__Register"
},
{
"key": "-",
"parent": "Identification__ImgRefFullPub"
},
{
"key": "DtAppDt",
"parent": "Dates__DtAppDt"
},
{
"key": "IdxNam",
"parent": "Description__IdxNam"
},
{
"key": "Clms",
"parent": "Description__Clms"
},
{
"key": "Disclaims",
"parent": "Description__Disclaims"
},
{
"key": "LglStsCd",
"parent": "Status__LglStsCd"
},
{
"key": "UsPtoStsCd",
"parent": "Status__UsPtoStsCd"
},
{
"key": "PtoStsCdDt",
"parent": "Status__PtoStsCdDt"
},
{
"key": "StsFlag",
"parent": "Status__StsFlag"
},
{
"key": "SrcInd",
"parent": "Status__SrcInd"
},
{
"key": "LglStsCdNorm",
"parent": "Status__LglStsCdNorm"
}
]
I want to convert it into this format which is nested json.
[
{
name: "Identification",
fields: [
{
"key": "AppNum",
"parent": "Identification__AppNum"
},
{
"key": "DataTp",
"parent": "Identification__DataTp"
},
{
"key": "DtOgWatchDt"
},
{
"key": "DtPendingWatchDt"
},
{
"key": "IssRef"
},
{
"key": "ImgRef"
},
{
"key": "Register"
},
{
"key": "ImgRefFullPub"
},
{
"key": "guid"
},
{
"key": "version"
},
{
"key": "offloadid"
},
{
"key": "reported"
},
{
"key": "control"
}
]
},
{
name: "Description",
fields: [
{
"key": "IdxNam"
},
{
"key": "Clms"
},
{
"key": "Disclaims"
}
]
},
{
name: "Status",
fields: [
{
"key": "UsPtoStsCd"
},
{
"key": "PtoStsCdDt"
},
{
"key": "LglStsCd"
},
{
"key": "StsFlag"
},
{
"key": "SrcInd"
},
{
"key": "LglStsCdNorm"
}
]
},
{
name: "Dates",
fields: [
{
"key": "DtAppDt"
}
]
}
]
As you can see according to parent key we have to create nested structure.
I have tried all the ways, I search a lot on google also, but hard luck.
Any help will be appreciated.
You'll want to create a new array of objects, then loop through the original array and add entries to the new array based on that. For example --
const input = [
{
"key": "guid",
"parent": "id__guid"
},
{
"key": "version",
"parent": "id__version"
}
// et cetera... your input
];
// these are buckets.
const transformedObject = {
"Identification": []
}
// First we put the data into the right buckets
input.forEach((entry) => {
// Create a new object with the key
const newObject = { key: entry.key };
// By default, the parent seems to be "Identification"
let parentKey = "Identification";
// Find out if the parent's name has an underscore?
if (entry.parent.split("__").length > 1) {
// If so, that's the new parent
parentKey = entry.parent.split("__")[0];
}
// If there isn't an array for this parent, make one
if (!transformedObject[parentKey]) {
transformedObject[parentKey] = [];
}
transformedObject[parentKey].push(newObject);
})
const output = [];
// Then we need to shape the data
Object.keys(transformedObject).forEach((parentKey) => {
const parentGroup = {
name: parentKey,
fields: transformedObject[parentKey]
};
output.push(parentGroup);
});
console.log(output);
You'll notice this doesn't get you all the way there. The "id" prefix seems to be merged into the "Identification" prefix, and you want to keep the parent value on some of these objects. You'll need some conditionals or a map or something to get that part working. But I hope this is a start!
Below is my Attempt, I have an object which has array of objects within it, it has a field: 'positionTitle'.
I also have an array of objects which also has a 'positionTitle'
They both have similar data I want all of the values for the positionTitles in my 'individualsData' to go into 'graphData' and be able to now use this new graphData!
I think my attempt is wrong its treating them both as arrays?
Thanks, Dale
graphData = {
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
}
]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "Adnan A. Khan"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "Christine Leong"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
What I expect to see:
NEWgraphData = {
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy" <== from individualsdata
}
}]
}]
}
]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Managing Director" <== also from individuals data
}
}]
}]
}
graphData.engagementAreas.map((el, i) => {
el.engagementTypes.engagements.members.position.positionTitle = individualsData.positions.positionTitle;
return el;
})
As engagementTypes, engagements and members properties are also array of objects, you have to loop them as well as below.
graphData.engagementAreas.map((el, i) => {
el.engagementTypes.forEach((et) => {
et.engagements.forEach((eg) => {
eg.members.forEach((mem) => {
mem.position.positionTitle = individualsData.positions.positionTitle; // make sure this is correct
});
});
});
return el;
})
Here is the solution. but you have to choose what individual data item will be the pick for the positionTitle
graphData.engagementAreas.map((el, i) => {
return el.engagementTypes.map((el2,i2) => {
return el2.engagements.map( (el3,i3) => {
return el3.members.map((el4,i4) => {
return el4.position.positionTitle =individualsDt[0].positions.[0].positionTitle;// take a look here, i just pick positionTitle staticly
})
})
})
});
see implementation in console here enter link description here
I'm very new to Javascript and have been given a task. I have a JSON feed that has been given as follows:
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
}
]
}
],
"branding": [{
"municipality_id": "01408.b",
"brand_color": "#f9cd90"
}, {
"municipality_id": "03442.f",
"brand_color": "#F28123"
}, {
"municipality_id": "01991.o",
"brand_color": "#D34E24"
}, {
"municipality_id": "01778.k",
"brand_color": "#563F1B"
}, {
"municipality_id": "02761.q",
"brand_color": "#38726C"
}],
"customer": {
"name": "Viktoria Tiedemann",
"date_of_birth": "1981-09-19",
"address": {
"street": "Schönfließer Str 9",
"suburb": "Prenzlauer Berg",
"postcode": "10439"
}
}
}
};
The task is simple - to find the suburb and the region of Viktoria Tiedemann. So far I've tried using the below:
var customer_suburb;
var customer_name = 'Viktoria Tiedemann';
for (var i = 0; i < data.feeds.customer.length; i++){
if (data.feeds.customer.name[i] == customer_name){
customer_suburb = data.feeds.customer.address.suburb;
}
}
but it keeps on returning undefined values - where am I going wrong? I'm thinking to use the same process to get the region.
In your data, you have just one customer — not an array of customers — which is accessible with:
data.feeds.customer
( if customer was supposed to be an array, you could find Viktoria with : let customer = data.feeds.customer.find(c => c.name === 'Viktoria Tiedemann') )
You can get the suburb with:
let suburb = data.feeds.customer.address.suburb
Once you have that, you just need to find() the region whose suburbs array has this. For that find() combined with some() does this succinctly:
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 }]}],"branding": [{"municipality_id": "01408.b","brand_color": "#f9cd90"},{"municipality_id": "03442.f","brand_color": "#F28123"},{"municipality_id": "01991.o","brand_color": "#D34E24"},{"municipality_id": "01778.k","brand_color": "#563F1B"},{"municipality_id": "02761.q","brand_color": "#38726C"}],"customer": {"name": "Viktoria Tiedemann","date_of_birth": "1981-09-19","address": {"street": "Schönfließer Str 9","suburb": "Prenzlauer Berg","postcode": "10439"}}}};
let suburb = data.feeds.customer.address.suburb
let region = data.feeds.regions.find(region => region.suburbs.some(s => s.name === suburb))
console.log("suburb:", suburb, "region:", region.name)
I have sample json. In that json I need to check the following things.
Valid Json or not.
Name key is required without empty(list name and item name).
items array length need to greater than 5.
I attached my code and its not working. I feel this approach is not good. Can anyone please suggest to me the correct path.
var test = '{ "lists": [ { "items": [ { "name": "Curd0", "sequence": 3 }, { "name": "Curd1", "sequence": 2 }, { "name": "Curd2", "sequence": 1 }, { "name": "Curd3", "sequence": 4 }, { "name": "Curd4", "sequence": 10 }, { "name": "Curd5", "sequence": 9 }, { "name": "Curd6", "sequence": 8 }, { "name": "Curd7", "sequence": 7 }, { "name": "Curd8", "sequence": 6 }, { "name": "Curd9", "sequence": 5 } ], "name": "Curd Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:18:26.169Z" }, { "items": [ { "name": "Milk0", "sequence": 3 }, { "name": "Milk1", "sequence": 2 }, { "name": "Milk2", "sequence": 1 }, { "name": "Milk3", "sequence": 4 }, { "name": "Milk4", "sequence": 10 }, { "name": "Milk5", "sequence": 9 }, { "name": "Milk6", "sequence": 8 } ], "name": "Milk Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:18:44.504Z" }, { "items": [ { "name": "Water0", "sequence": 3 }, { "name": "Water1", "sequence": 2 }, { "name": "Water2", "sequence": 1 }, { "name": "Water3", "sequence": 4 }, { "name": "Water4", "sequence": 10 }, { "name": "Water5", "sequence": 9 }, { "name": "Water6", "sequence": 8 } ], "name": "Water Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:19:02.329Z" }, { "items": [ { "name": "Fruit0", "sequence": 3 }, { "name": "Fruit1", "sequence": 2 }, { "name": "Fruit2", "sequence": 1 }, { "name": "Fruit3", "sequence": 4 } ], "name": "Fruit Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:19:15.503Z" } ] }';
function Validate(data, callback) {
for (index in lists) {
if (!lists.index.hasOwnProperty('name')) {
callback("Name cannot be empty");
}
var itemList = lists.index.items;
if (itemList.length < 5) {
callback("List need more than 5 lenth");
}
for ( i = 0; i < itemList.length; i++) {
if (!itemList[i].hasOwnProperty('name')) {
callback("Item Name cannot be empty");
}
}
}
callback(null);
}
Validate(test, function (err) {
console.log(err);
});
every is probably what you need :
function containsNameInLists(element) {
return element.hasOwnProperty('name');
}
function containsNameInItems(element) {
return element.items.every(containsKeyName);
}
function containsKeyName(element) {
return element.hasOwnProperty('name');
}
function lengthSuperiorTo5(element) {
return element.length > 5;
}
function itemsArrayLength(){
return element.items.every(lengthSuperiorTo5);
}
You can test if your string is a valid JSON string simply using JSON.parse
Try to play with the string to test different functions.
Demo
EDIT : I've added the additionnal functions :
EDIT DEMO
The callback will call multiple times, please add a "return":
return callback(...);
For validate json in node.js, there is a good library: https://github.com/hapijs/joi