Json structure with Javascript Mapping - javascript

Is any tool or online editor available so that it specify how to access a json element.For example if i provide json as input ,then we should get an output which will specify each item how can we access through javascript
Example
Assume Input is
var myList={ "vehicleList": { "Vehicle": [ { "vehicleId": 88, "vehicleName": "veh1", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1001, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1002, "AlertName": "Sudden acceleration", "Alertcount": 40 } ] }, { "vehicleId": 87, "vehicleName": "veh2", "totalEvents": 11, "medium": 4, "Severe": 7, "Category": [ { "AlertId": 1003, "AlertName": "Overspeed", "Alertcount": 30}, { "AlertId": 1004, "AlertName": "Drunk", "Alertcount": 10 } ] }, { "vehicleId": 87, "vehicleName": "veh3", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1007, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1008, "AlertName": "Overspeed", "Alertcount": 77 } ] }, { "vehicleId": 86, "vehicleName": "veh4", "totalEvents": 11, "medium": 4, "Severe": 5, "Category": [ { "AlertId": 1009, "AlertName": "Overspeed", "Alertcount": 17 }, { "AlertId": 1010, "AlertName": "HighSpeed", "Alertcount": 10 } ] } ] } };
Output should be a structure,which will specify like
myList.vehicleList.Vehicle[3].Severe;

It seems like you looking backward means providing the value you need what will be the expression to get the value. I don't have a solution for that.
But I would like to suggest json is very easy to read, may be you are having trouble due to long chunk of string. Try this website(editor) http://jsonlint.com/ this will validate your json and give you in more readable form. Hope this will help you in one or other way.

Related

How to sort an array of object properties? or turn object properties upside down

Hey guys kind of ran into a problem and would like some help.... I am having trouble trying to replicate this array of objects...
{
"recipe_id" : 1,
"recipe_name": "Spaghetti Bolognese",
"created_at": "2021-01-01 08:23:19.120",
"steps": [
{
"step_id": 11,
"step_number": 1,
"step_instructions": "Put a large saucepan on a medium heat",
"ingredients": []
},
{
"step_id": 12,
"step_number": 2,
"step_instructions": "Add 1 tbsp olive oil",
"ingredients": [
{ "ingredient_id": 27, "ingredient_name": "olive oil", "quantity": 0.014 }
]
},
]
}
The result that I am getting is something like this
{
"created_at": "2021-01-03 09:08:19.150",
"recipe_id": 2,
"recipe_name": "chicken nuggets",
"steps": [
{
"ingredients": [],
"step_id": 7,
"step_instructions": "Go to backyard",
"step_number": 1
},
{
"ingredients": [],
"step_id": 8,
"step_instructions": "find a chicken",
"step_number": 2
},
{
"ingredients": [],
"step_id": 9,
"step_instructions": "take its nuggets",
"step_number": 3
},
{
"ingredients": [],
"step_id": 10,
"step_instructions": "season nuggets with spices",
"step_number": 4
},
{
"ingredients": [],
"step_id": 10,
"step_instructions": "season nuggets with spices",
"step_number": 4
},
{
"ingredients": [],
"step_id": 11,
"step_instructions": "cook for 30 minute till done",
"step_number": 5
}
]
}
The way I am doing this is like this :
async function getRecipeById(recipeId){
const recipe = await db('recipes as r')
.join('steps as s','s.recipe_id','r.recipe_id')
.leftJoin('step_ingredients as si', 'si.recipe_steps_id', 's.recipe_steps_id')
.leftJoin('ingredients as i', 'i.ingredient_id', 'si.ingredient_id')
.select('r.*','s.recipe_steps_id','s.recipe_steps_number','s.recipe_step_instructions','i.ingredient_id','i.ingredient_name','si.step_ingredient_quantity')
.where('r.recipe_id',recipeId)
const result = {
recipe_id: recipe[0].recipe_id,
recipe_name: recipe[0].recipe_name,
created_at: recipe[0].createdAt,
steps: []
}
let ingredients = []
recipe.forEach(step => {
if(step.recipe_steps_id){
result.steps.push({
step_id: step.recipe_steps_id,
step_number: step.recipe_steps_number,
step_instructions: step.recipe_step_instructions,
ingredients: ingredients
})
}
});
return result
When I create a way to implement the ingredient into my work it ends up going upside down pretty much..
"created_at": "2021-01-03 09:08:19.150",
"recipe_id": 2,
"recipe_name": "chicken nuggets",
"steps": [
{
"ingredients": [
{
"ingredient_id": 5,
"quantity": 50,
"step_number": "chicken"
}
],
"step_id": 7,
"step_instructions": "Go to backyard",
"step_number": 1
},
{
"ingredients": [
{
"ingredient_id": 5,
"quantity": 50,
"step_number": "chicken"
}
],
"step_id": 8,
"step_instructions": "find a chicken",
"step_number": 2
},
{
"ingredients": [
{
"ingredient_id": 8,
"quantity": 250,
"step_number": "nuggets"
},
{
"ingredient_id": 10,
"quantity": 50,
"step_number": "spices"
}
],
"step_id": 9,
"step_instructions": "take its nuggets",
"step_number": 3
},
{
"ingredients": [
{
"ingredient_id": 8,
"quantity": 250,
"step_number": "nuggets"
},
{
"ingredient_id": 10,
"quantity": 50,
"step_number": "spices"
}
],
"step_id": 10,
"step_instructions": "season nuggets with spices",
"step_number": 4
},
{
"ingredients": [
{
"ingredient_id": 8,
"quantity": 250,
"step_number": "nuggets"
},
{
"ingredient_id": 10,
"quantity": 50,
"step_number": "spices"
}
],
"step_id": 10,
"step_instructions": "season nuggets with spices",
"step_number": 4
},
I added this piece of code to pretty much push the ingredients into an array and if there is no ingredient name it would return an empty array
if(step.ingredient_name && step.ingredient_name !== null){
ingredients.push({
ingredient_id: step.ingredient_id,
step_number: step.ingredient_name,
quantity: step.step_ingredient_quantity
})
}else{
ingredients = []
}
My question is how can I pretty much reverse the way the results are being printed out...inside the steps array. I can see that it is alphabetically, I want to get it looking the way the example above was shown... Im am using javascript for this and build a DB with knex as well as using SQL for DB....
At the same time if you can help with my code where if its null i don't have the ingredients printed out twice like it did with chicken if you see that
If you want to add to the beginning of the ingredients array, just do:
ingredients.unshift(object)
You can also reverse an array completely with
ingredients.reverse()
But if you want to sort the objects by a certain property, look at the JavaScript sort method. You can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Retrive Value from nested object using recursion

I have an JS object data, from this array of object, I need to take "amount" value which is inside of "limitBreakup" Array. I have done using .map(), But I am intersted to know the implementation of the same using Recursion.
var data = [
{
"limitRequirementId":"123",
"facilityType":"cc",
"amount":800000,
"existingRoi":12,
"existingPf":12100,
"repoRate":5,
"spread":10,
"tenure":24,
"margin":10000,
"loanVariable":{
"type":"roi/commission",
"value":15
},
"limitBreakup":[
{
"limitRequirementId":"13",
"facilityType":"cc",
"repoRate":5,
"amount":8000,
"spread":10,
"tenure":24,
"margin":100,
"loanVariable":{
"type":"roi/commission",
"value":15
}
},
{
"limitRequirementId":"22",
"facilityType":"LC",
"repoRate":4,
"amount":900,
"spread":6,
"tenure":21,
"margin":15,
"loanVariable":{
"type":"roi/commission",
"value":10
}
}
]
},
{
"limitRequirementUniqueId":"13",
"limitRequirementId":"13",
"facilityType":"lc",
"amount":900000,
"existingRoi":10,
"existingPf":1000,
"repoRate":3,
"spread":1,
"tenure":21,
"margin":1000,
"loanVariable":{
"type":"roi/commission",
"value":15
},
"limitBreakup":[
{
"limitRequirementId":"35",
"facilityType":"CC",
"repoRate":6,
"amount":600,
"spread":8,
"tenure":28,
"margin":13,
"loanVariable":{
"type":"roi/commission",
"value":14
}
}
]
}
]
My Solution using normal iteration works:
data.forEach((d, i)=>{
let limitBreakup = d.limitBreakup;
if(Array.isArray(limitBreakup)){
limitBreakup.forEach((l)=>{ console.log(l, '->', l.amount) })
}else{
console.log(limitBreakup, 'else->', limitBreakup.amount)
}
//console.log(d.limitBreakup);
})
But using Recursion, I am half way:
https://jsfiddle.net/1g98sLw3/2/
http://www.mocky.io/v2/5ea974eb3400005e003f0203 (Since the json object is very big, I have pasted in mocky.io for reference)
Something like this should work
Demo proof: https://jsfiddle.net/do58kj3q/
You need a loop to pass through your objects and then add them to the array when you meet the criteria
var data = [{
"limitRequirementId": "123",
"facilityType": "cc",
"amount": 800000,
"existingRoi": 12,
"existingPf": 12100,
"repoRate": 5,
"spread": 10,
"tenure": 24,
"margin": 10000,
"loanVariable": {
"type": "roi/commission",
"value": 15
},
"limitBreakup": [{
"limitRequirementId": "13",
"facilityType": "cc",
"repoRate": 5,
"amount": 8000,
"spread": 10,
"tenure": 24,
"margin": 100,
"loanVariable": {
"type": "roi/commission",
"value": 15
}
},
{
"limitRequirementId": "22",
"facilityType": "LC",
"repoRate": 4,
"amount": 900,
"spread": 6,
"tenure": 21,
"margin": 15,
"loanVariable": {
"type": "roi/commission",
"value": 10
}
}
]
},
{
"limitRequirementUniqueId": "13",
"limitRequirementId": "13",
"facilityType": "lc",
"amount": 900000,
"existingRoi": 10,
"existingPf": 1000,
"repoRate": 3,
"spread": 1,
"tenure": 21,
"margin": 1000,
"loanVariable": {
"type": "roi/commission",
"value": 15
},
"limitBreakup": [{
"limitRequirementId": "35",
"facilityType": "CC",
"repoRate": 6,
"amount": 600,
"spread": 8,
"tenure": 28,
"margin": 13,
"loanVariable": {
"type": "roi/commission",
"value": 14
}
}]
}
]
var array=[];
function recursiveCounter(arr) {
for (let i = 0; i < arr.length; i++) {
const obj = arr[i];
if (!obj.limitBreakup) {
array.push(obj.amount);
}
if (Array.isArray(obj.limitBreakup)) {
recursiveCounter((obj.limitBreakup));
}
}
}
recursiveCounter(data);
console.log(array)

How to turn object values into new array in JavaScript

I am trying to simplify the following state:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [
{
"slot": 1,
"type": {
"name": "poison",
"url": "https://poke"
}
},
{
"slot": 2,
"type": {
"name": "grass",
"url": "https://poke"
}
}
]}
into something like this:
{
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types": [ "poison", "grass" ]
}
Also, I would like to mention that I have an array with 151 of these. Not every object contains two types; some only contain one.
I believe that is the reason most of what I have tried so far does not work. Thank you in advance for your help.
Try using map
let obj={ name: "bulbasaur", picture: "https://raw", height: 7, weight: 69, types : [{ slot: 1, type: { name: "poison", url:"https://poke" }}]};
obj.types=obj.types.map( Type => Type.type.name);
console.log(obj.types);
I think this is what you want, you will need to add this snippet in a loop for you dataset and have it pushed into a new array:
const Obj = {
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)
I was able to resolve what I needed by using the logic provided by Ma'moun othman.
"name": "bulbasaur",
"picture": "https://raw",
"height": 7,
"weight": 69,
"types" : [{
"slot": 1,
"type": {
"name": "poison",
"url":"https://poke"
}}, {
"slot": 2,
"type": {
"name": "grass",
"url":"https://poke"
}}
]};
const newObj = {
...Obj,
types: Obj.types.map((el) => el.type.name),
}
console.log(newObj)

Push data to array without using if statement

I have following output. it gives my API.
{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}}
I want to Push them to arrays according to method. As an example
twoHundArray=[
{ "x":2018,6,11,12,45,
"y" :1},
{"x": 2016,11,11,17,10 ,
"y" :47}]
fourhundrArry=[{ "x":2018,11,11,16,50,
"y" :5}]
without using if/else statement how to push them to different arrays. In here I don't know all the names of methods.so cannot use if statement for "method".that is the problem here.
The original object is invalid. You can't have elements in an object without specifying the keys. I've assumed that it is an array.
Secondly, there is no way of pushing elements to different arrays without knowing their names. So the judgement of pushing the elements to different variables will have to be based on if/else conditions. Additionally, creation of those variables will vary based on the groups, as method could have been any value.
If you agree to group the objects based on the values method have, here is a way to do this:
const data = [{"_id":{"year":2018,"month":6,"day":11,"hour":12,"interval":45,"method":"200"},"count":1},{"_id":{"year":2016,"month":11,"day":11,"hour":16,"interval":50,"method":"404"},"count":5},{"_id":{"year":2016,"month":11,"day":11,"hour":17,"interval":10,"method":"200"},"count":47}];
const res = {};
data.forEach(item => {
const { method, ...obj } = item['_id'];
res[method] = res[method] || [];
res[method].push({
x: Object.values(obj),
y: item.count
});
});
console.log(res);
It creates an object, whose keys are method. The values in the object are the arrays, which contain the items grouped by method.
You can use Array.reduce and create a map based on method. Try the following:
var data = [{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}];
var method = data.reduce((a,o)=>{
if(!a[o._id.method]){
a[o._id.method] = [];
};
var { method, ...ob } = o._id;
a[o._id.method].push({
"x": Object.values(ob).join(","),
"y" : o.count
});
return a;
}, {});
console.log(method);
You can create an object with status:values key/pair using Array.reduce and post that using Object destructuring and default assignment, create independent variables.
const arr = [{"_id":{"year":2018,"month":6,"day":11,"hour":12,"interval":45,"method":"200"},"count":1},{"_id":{"year":2016,"month":11,"day":11,"hour":16,"interval":50,"method":"404"},"count":5},{"_id":{"year":2016,"month":11,"day":11,"hour":17,"interval":10,"method":"200"},"count":47}];
let obj = arr.reduce((a,c) => {
a[c._id.method] = a[c._id.method] || [];
a[c._id.method].push({"x" : Object.values(c._id).join(), "y" : c.count});
return a;
},{});
/* You can add an entry here for every status type, it will pick the
** value from object and if not present will be defaulted to an empty array */
const {200 : twoHundArray=[], 404 : fourHundArray=[], 300 : threeHundArray=[]} = obj;
console.log(twoHundArray);
console.log(fourHundArray);
console.log(threeHundArray);
#Palani, I'll suggest you to use an object to gather all the required information.
Please have a look at the below code and let me know any suggestions/modifications if you need.
var timeDataArr = [
{
"_id": {
"year": 2018,
"month": 6,
"day": 11,
"hour": 12,
"interval": 45,
"method": "200"
},
"count": 1
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 16,
"interval": 50,
"method": "404"
},
"count": 5
},
{
"_id": {
"year": 2016,
"month": 11,
"day": 11,
"hour": 17,
"interval": 10,
"method": "200"
},
"count": 47
}
]
// An object that maps 'method' to its related data array
var newTimeData = {}
for(var timeData of timeDataArr) {
var obj = timeData["_id"];
var arr = [obj["year"], obj["month"], obj["day"], obj["hour"], obj["interval"]];
var newObj = {
"x": arr.join(", "),
"y": timeData["count"],
}
if(newTimeData[obj["method"] + "Array"]) { // method found
newTimeData[obj["method"] + "Array"].push(newObj)
} else { // method not found
newTimeData[obj["method"] + "Array"] = [newObj]
}
}
// PRETTY PRINTING OBJECT
console.log(JSON.stringify(newTimeData, undefined, 4))
/*...
{
"200Array": [
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
],
"404Array": [
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
}
...*/
// PRETTY PRINTING ARRAY POINTED BY '200Array' key
console.log(JSON.stringify(newTimeData["200Array"], undefined, 4))
/*...
[
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
]
...*/
// PRETTY PRINTING ARRAY POINTED BY '404Array' key
console.log(JSON.stringify(newTimeData["404Array"], undefined, 4))
/*...
[
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
...*/
Output ยป
H:\RishikeshAgrawani\Projects\Sof\FilterArrays>node FilterArrays.js
{
"200Array": [
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
],
"404Array": [
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]
}
[
{
"x": "2018, 6, 11, 12, 45",
"y": 1
},
{
"x": "2016, 11, 11, 17, 10",
"y": 47
}
]
[
{
"x": "2016, 11, 11, 16, 50",
"y": 5
}
]

Array transformation in D3

What is best way to transform array from this
[{
"state": "vic",
"age_group_1": 10,
"age_group_2": 20,
"age_group_3": 30,
"age_group_4": 40,
"age_group_5": 50,
}, {
"state": "nsw",
"age_group_1": 60,
"age_group_2": 70,
"age_group_3": 80,
"age_group_4": 90,
"age_group_5": 100,
}, {
"state": "tas",
"age_group_1": 11,
"age_group_2": 21,
"age_group_3": 31,
"age_group_4": 41,
"age_group_5": 51,
}, {
"state": "qld",
"age_group_1": 61,
"age_group_2": 71,
"age_group_3": 81,
"age_group_4": 91,
"age_group_5": 101,
}]
to this
[{
"age_group": "age_group_1",
"states": [{
"name": "vic",
"value": 10
}, {
"name": "nsw",
"value": 60
}, {
"name": "tas",
"value": 11
}, {
"name": "qld",
"value": 61
}]
}, {
"age_group": "age_group_2",
"states": [{
"name": "vic",
"value": 20
}, {
"name": "nsw",
"value": 70
}, {
"name": "tas",
"value": 21
}, {
"name": "qld",
"value": 71
}]
}, {
"age_group": "age_group_3",
"states": [{
"name": "vic",
"value": 30
}, {
"name": "nsw",
"value": 80
}, {
"name": "tas",
"value": 31
}, {
"name": "qld",
"value": 81
}]
}, {
"age_group": "age_group_5",
"states": [{
"name": "vic",
"value": 40
}, {
"name": "nsw",
"value": 90
}, {
"name": "tas",
"value": 41
}, {
"name": "qld",
"value": 91
}]
}, {
"age_group": "age_group_5",
"states": [{
"name": "vic",
"value": 50
}, {
"name": "nsw",
"value": 100
}, {
"name": "tas",
"value": 51
}, {
"name": "qld",
"value": 101
}]
}]
using simple javascript and looping I can do but I want to use either d3 functions or may be any other library that deal with data transformation.
Which is best library for data transformation.
You could use a temporary object for the reference to the result array.
var data = [{ "state": "vic", "age_group_1": 10, "age_group_2": 20, "age_group_3": 30, "age_group_4": 40, "age_group_5": 50, }, { "state": "nsw", "age_group_1": 60, "age_group_2": 70, "age_group_3": 80, "age_group_4": 90, "age_group_5": 100, }, { "state": "tas", "age_group_1": 11, "age_group_2": 21, "age_group_3": 31, "age_group_4": 41, "age_group_5": 51, }, { "state": "qld", "age_group_1": 61, "age_group_2": 71, "age_group_3": 81, "age_group_4": 91, "age_group_5": 101, }],
result = [];
data.forEach(function (a) {
Object.keys(a).forEach(function (k) {
if (k !== 'state') {
if (!this[k]) {
this[k] = { age_group: k, states: [] };
result.push(this[k]);
}
this[k].states.push({ name: a.state, value: a[k] });
}
}, this);
}, {});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Take advantage of modern JS instead of trying to make D3 do it - it's pretty simple code:
var basedata = the original array from your question;
// I assume your data already has this array of categories somewhere,
// but if it doesn't, let's just declare it here:
var age_groups = [
"age_group_1",
"age_group_2",
"age_group_3",
"age_group_4",
"age_group_5"
];
var transformed = age_groups.map(group => {
return {
age_group: group,
states: basedata.map(set => {
return { state: set.state, value: set[group] }
})
};
});
And done.
The reason this works is because you want objects keyed on your age groups, so we start by making sure we create a mapping based on those. Then, for each age group, we simply run through the base data and return the state/value pair. Nothing really complex, and ES6/ES2015 does the job for us.
Don't like ES6/ES2015? Good opportunity to get with the times, but also really easily rewritten to older ES5 format: replace each (...) => { ... } with function(...) { return ... } and done.
You can try something like this:
var data=[{state:"vic",age_group_1:10,age_group_2:20,age_group_3:30,age_group_4:40,age_group_5:50},{state:"nsw",age_group_1:60,age_group_2:70,age_group_3:80,age_group_4:90,age_group_5:100},{state:"tas",age_group_1:11,age_group_2:21,age_group_3:31,age_group_4:41,age_group_5:51},{state:"qld",age_group_1:61,age_group_2:71,age_group_3:81,age_group_4:91,age_group_5:101}];
var _tmp = {}
var kepReg = /^age_group/;
data.forEach(function(item) {
for (var k in item) {
if (kepReg.test(k)) {
if (!_tmp[k])
_tmp[k] = {
state: []
};
_tmp[k].state.push({
name: item["state"],
value: item[k]
})
}
}
});
var result = Object.keys(_tmp).map(function(k) {
return {
age_group: k,
states: _tmp[k].state
}
});
document.write("<pre>" + JSON.stringify(result, 0, 4) + "</pre>")

Categories

Resources