Reduce array of json to json object - arrays

I have details as
data = {
name: "charles",
id: "1",
education: [
{"class": "X","marks": 223,"percentage": "59%"},
{"class": "IX","marks": 223,"percentage": "59%"},
{"class": "IIX","marks": 223,"percentage": "59%"},
{"class": "IIIX","marks": 223,"percentage": "59%"}
]
}
My desired result need is to break into 4 json objects
{name:"charles",id:"1", education:{"class":"X","marks":223,"percentage":59%}}
{name:"charles",id:"1", education:{"class":"IX","marks":223,"percentage":59%}}
Can anyone let me know how to achieve it?
I am sucessfully by looping and creating each object induvidually as follows:
this.data.education.forEach( class => {
const newData: any = {};
newData.name= data.name;
newData.id= data.id;
newData.education = class ;
array.push(newData);
});
I am looking for any simplist way of achieving it?

You need to extract name and id and pass along all entries of education array. Hope this helps
const data = { name: "charles", id: "1", education: [
{ "class": "X", "marks": 223, "percentage": 59 },
{ "class": "IX", "marks": 223, "percentage": 59 },
{ "class": "IIX", "marks": 223, "percentage": 59 },
{ "class": "IIIX", "marks": 223, "percentage": 59 }
]
};
const {name, id} = data;
const response = data.education
.reduce((result, education) => ([...result, {name, id, education}]), []);
console.log(response)

const newData = data.education
.map(e => ({ id: data.id, name: data.name, education: e}))

Related

Using multiple forEach chained into each other and iterating over a single array, Need an equivalent method to handle the same without forEach looping

My array contains multiple arrays and to access the objects, I have used multiple forEach. How do I handle using multiple foreach loops?
Kindly suggest an equivalent method to avoid this chaining.
See the below snippet and suggest a better solution to optimize my code.
var v = [
{
"company_name": "Apple",
"company_code": "AP",
"states": [
{
"state_name": "California",
"state_code": "CA",
"locations": [
{
"location_name": "USA - New York",
"location_code": "US - NY"
},
{
"location_name": "USA - San Francisco",
"location_code": "US - SF"
}
]
},
{
"state_name": "Rajasthan",
"state_code": "RJ",
"locations": [
{
"location_name": "Udaipur",
"location_code": "UDR"
},
{
"location_name": "Jaipur",
"location_code": "JP"
}
]
}
]
}
]
var AllData=[]
for (let i = 0; i < v.length; i++) {
const data = v[i];
//console.log(data);
data.states.forEach((state) => {
state.locations.forEach((location) => {
const ELEMENT_DATA = {
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name,
};
AllData.push(ELEMENT_DATA);
});
});
}
console.log(AllData);
Not really an optimisation, more of a readability improvement:
const arr = v.map(data =>
data.states.map(state =>
state.locations.map(location =>
({
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name
})
)
)
);
Check the following snippet to see if the output is the same.
var v = [{
"company_name": "Apple",
"company_code": "AP",
"states": [{
"state_name": "California",
"state_code": "CA",
"locations": [{
"location_name": "USA - New York",
"location_code": "US - NY"
},
{
"location_name": "USA - San Francisco",
"location_code": "US - SF"
}
]
},
{
"state_name": "Rajasthan",
"state_code": "RJ",
"locations": [{
"location_name": "Udaipur",
"location_code": "UDR"
},
{
"location_name": "Jaipur",
"location_code": "JP"
}
]
}
]
}]
const arr = v.map(data =>
data.states.map(state =>
state.locations.map(location =>
({
companyname: data.company_name,
statename: state.state_name,
locationname: location.location_name
})
)
)
);
console.log(arr)
This is basically your code, looping on each of the properties, it is just more easy to read.

EDIT-How can I have my specific format using Object.entries?

I have these data from my api (1) and the format I want to have is this one(2), how can I do that in my front-end using Object.entries in REACT, in such a way I can modify my (1) to have (2) please ? I tried but not working...
(1):
{
"myData": [
{
"Peter": 12,
"Donald": 15,
"Huston": 65
}
],
"myOtherData": [
{
"location": "Dublin",
"country":"Irland"
}
]
}
(2):
{
"myData": [
{
"name": "Peter",
"age": "12"
},
{
"name": "Donald",
"age": "15"
},
{
"name": "Huston",
"age": "65"
}
],
"myOtherData": [
{
"location": "Dublin",
"country":"Irland"
}
]
}
I was thinking using destructuration like this :
const d= {myData, myOtherData}
const newData = Object.entries(...)//change myData here ??
Lets be fancy, time to utilise flatMap, array deconstruction and some shortcuts
const a = {
"myData": [{
"Peter": 12,
"Donald": 15,
"Huston": 65
}]
}
console.log({
myData: Object.entries(a.myData[0])
.flatMap(([name, age]) => ({
name,
age
}))
})
const resp = {
"myData": [{
"Peter": 12,
"Donald": 15,
"Huston": 65
}]
}
convertedData = []
for (const person of Object.entries(resp.myData[0])) {
convertedData.push({
name: person[0],
age: person[1]
})
}
const data = {
"myData": [{
"Peter": 12,
"Donald": 15,
"Huston": 65
}]
}
console.log(
Object.entries(data.myData[0])
.reduce( (acc,[name,age])=>acc.concat({name,age}),[] )
)
lets say
var myData = {
"Peter": 12,
"Donald": 15,
"Huston": 65
}
var finalData = Object.entries(myData).map(entry => {
const[key,value] = entry;
return {
name:key,
age:value
}
})
console.log(finalData)

Separate an object in a array of objects

Im consuming data from an API
"stats": [
{
"base_stat": 48,
"effort": 1,
"stat": {
"name": "hp",
"url": "https://pokeapi.co/api/v2/stat/1/"
}
},
{
"base_stat": 48,
"effort": 0,
"stat": {
"name": "attack",
"url": "https://pokeapi.co/api/v2/stat/2/"
}
}]
So when i recieve this, im doing =>
const selectedStats = stats.reduce(
(acc, stat) => ({ ...acc, [stat.stat.name]: stat.base_stat }),
{} );
// OUTPUT => stats: {
attack: 48
hp: 48 }
But now im trying to separate an object in a array of objects, like
[{attack: 81}, {hp: 48}, etc]
but i don't know how to do it
Sorry if this is a large question but i don't get the solve. Thanks!
Just mapping the result of Object.entries() would do it:
const stats = {
attack: 48,
hp: 48
};
const data = Object.entries(stats).map(([k, v]) => ({[k]: v}));
console.log(data);
You don't need the intermediate reduce() though. Since you're starting off with an array, you can do everything in a single map() operation:
const stats = [{
"base_stat": 48,
"effort": 1,
"stat": {
"name": "hp",
"url": "https://pokeapi.co/api/v2/stat/1/"
}
}, {
"base_stat": 48,
"effort": 0,
"stat": {
"name": "attack",
"url": "https://pokeapi.co/api/v2/stat/2/"
}
}];
const data = stats.map(({base_stat, stat: {name}}) => ({[name]: base_stat}));
console.log(data);

How to loop array after process groupBy in React-Native

i want to grouping data JSON (One JSON) base on region. and the json after grouping like in (Two JSON). and i use the two JSON for show data (Result JSON). so, how to add loop base on region after grouping, because actually i want to show data in front end like (Result JSON):
==>One JSON
data:[
{id:1,
status: "active",
dataDetail: {
id: 5,
name: tes 1,
region: aaa,
}
},
{id:2,
status: "active",
dataDetail: {
id: 8,
name: tes 2,
region: bbb,
}
},
{id:3,
status: "active",
dataDetail: {
id: 8,
name: tes 3,
region: aaa,
}
}
]
==> Two JSON
aaa: [
{id:1,
status: "active",
dataDetail: {
id: 5,
name: tes 1,
region: aaa,
}
},
{id:3,
status: "active",
dataDetail: {
id: 8,
name: tes 3,
region: aaa,
}
}
],
bbb: [
{id:2,
status: "active",
dataDetail: {
id: 8,
name: tes 2,
region: bbb,
}
},
]
==> Result JSON
aaa:
1
3
bbb:
2
thanks
Using Lodash:
const jsonTwo = _.groupBy(data, instance => instance.dataDetail.region);
const resultJson = _.mapValues(jsonTwo, regionInstances => regionInstances.map(instance => instance.id));
Using plain javascript reduce functions:
const jsonTwo = data.reduce((accumulator, instance) => {
if(!accumulator[instance.dataDetail.region]) {
accumulator[instance.dataDetail.region] = [];
}
accumulator[instance.dataDetail.region].push(instance)
return accumulator;
},{});
const resultJson = data.reduce((accumulator, instance) => {
if(!accumulator[instance.dataDetail.region]) {
accumulator[instance.dataDetail.region] = [];
}
accumulator[instance.dataDetail.region].push(instance.id)
return accumulator;
},{});
var data =
[
{
"id": 1,
"status": "active",
"dataDetail": {
"id": 5,
"name": "tes 1",
"region": "aaa"
}
},
{
"id": 2,
"status": "active",
"dataDetail": {
"id": 8,
"name": "tes 2",
"region": "bbb"
}
},
{
"id": 3,
"status": "active",
"dataDetail": {
"id": 8,
"name": "tes 3",
"region": "aaa"
}
}
];
groups =_.chain(data).groupBy('dataDetail.region');
keys = groups.map( (value, key) => key);
values = groups.map( (value, key) => _.map(value, 'id'));
result = _.zipObject(keys, values);

How to fetch data from json in angularjs Form

How to call the data from json in angularjs form without using backend. i have written this code and here m unable to find a way in last to get data from the json file. someone please help me to move forward from here.
code
$scope.count = $scope.newPreAuth.length;
};
//Delete newPreAuth - Using AngularJS splice to remove the preAuth row from the newPreAuth list
//All the Update newPreAuth to update the locally stored newPreAuth List
//Update the Count
$scope.deletenewPreAuth = function (preAuth) {
$scope.newPreAuth.splice($scope.newPreAuth.indexOf(preAuth), 1);
getLocalStorage.updatenewPreAuth($scope.newPreAuth);
$scope.count = $scope.newPreAuth.length;
};
}]);
//Create the Storage Service Module
//Create getLocalStorage service to access UpdateEmployees and getEmployees method
var storageService = angular.module('storageService', []);
storageService.factory('getLocalStorage', function () {
var newPreAuthList = {};
return {
list: newPreAuthList,
updatenewPreAuth: function (newPreAuthArr) {
if (window.localStorage && newPreAuthArr) {
//Local Storage to add Data
localStorage.setItem("newPreAuth", angular.toJson(newPreAuthArr));
}
newPreAuthList = newPreAuthArr;
},
getnewPreAuth: function () {
//Get data from Local Storage
newPreAuthList = angular.fromJson(localStorage.getItem("newPreAuth"));
return newPreAuthList ? newPreAuthList : [];
}
};
});
Json Code
PreAuth:
======================
URL:http://dev.xxx.com:8080/xxx/preAuth
TYPE:POST
X-Auth-Token t3Z10HGEiYFdzq9lGtr18ycdeAAXmWBEI64rQAJcAte6Ka8Tz96IAhuXHSgpiKufsd
{
"preAuth": {
"claimbId": "newPreAuth",
"claimbStatus": "new",
"patientInfo": {
"patientName": "name",
"gender": "Male",
"dob": 950639400000,
"age": 21,
"contactNumber": 9987654356,
"tpaMemberId": 950639400121,
"policyNumber": "ABC12615627",
"corporateName": "ABC",
"EmployeeId": "XYZ10232",
"otherInsurance": {
"isOtherInsurance": true,
"playerName": "xyx",
"details": "sdfdsafdsfdsf"
},
"familyPhysician": {
"isFamilyPhysician": true,
"physicianName": "fsdf"'c
"physicianContactNumber": 7878748728,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"isFamilyPhysician": false,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"medicalInfo": {
"illnessType": "cancer",
"clinicalFinding": "description",
"ailmentDuration": "2 months",
"ailmentHistory": "description",
"illnessCause": "alcohol",
"provisionalDiagnosis": [
{
"diagnosisName": "abc",
"diagnosisICDCode": "121423"
},
{
"diagnosisName": "xyz",
"diagnosisICDCode": "434543"
}
],
"differentialDiagnosis": [
{
"diagnosisName": "afasdbc",
"diagnosisICDCode": "12431423"
},
{
"diagnosisName": "fdxyz",
"diagnosisICDCode": "434sdf543"
}
],
"clinicalObservations": {
"BP": "120/80",
"CVS": "126",
"P.A.": "abc",
"R.S.": "aa",
"CNS": "dd",
"others": "others"
},
"maternityDetails": {
"maternityType": "G",
"L.M.P.": 950639400000,
"E.D.D.": 950639400000
},
"accidentDetails": {
"accidentCause": "xyz",
"accidentDate": 950639400000,
"isPoliceComplaint": true,
"firNumber": "asfsafds"
},
"pastIllness": [
{
"pastIllnessType": "Diabetes",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Hypertension",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Other",
"isPresent": false,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
}
]
},
"treatmentInfo": {},
"billingInfo": {},
"documents": [
{
"documentId": 12345,
"documentMetadata": {
"documentName": "discharge summary",
"date": 950639400000,
"version": "1.1",
"viewedStatus": false,
"link": "link to view/download document"
}
},
{
"documentId": 12346,
"documentMetadata": {
"documentName": "medical summary",
"date": 950639400000,
"version": "1.0",
"viewedStatus": true,
"link": "link to view/download document"
}
}
]
}
}
I created sample ,it worked this way
// Code goes here
var app = angular.module('app',[]);
app.controller('sample', function($scope,$http){
$scope.name = "advaitha";
$http.get('test.json').then(function(data){
console.log(data.data);
});
})
here is the plunker example
using HTML5 localStorage would require you to serialize and deserialize your objects before using or saving them.
For example:
var myObj = {
firstname: "kisun",
lastname: "rajot",
website: "https://www.kisun.com"
}
//if you wanted to save into localStorage, serialize it
window.localStorage.set("empData", JSON.stringify(myObj));
//unserialize to get object
var myObj = JSON.parse(window.localStorage.get("empData"));
Created a plunker based on your code am able save and retrieve the json data with your code. Please check here

Resources