Rearrange json with sample data - javascript

Original json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Expected json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
"Country": [
{
"Orientation": "Male",
"Name": ABCD
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female"
"Country": [
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Program:
//Original JSON data in question.
var Implementations = {
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
// Program that make the conversion
var finalResult = [];
for (var i=0; i<Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j=0; j<currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
console.log(JSON.stringify(finalResult));
How do I add the objects like Personality Traits, Eating Habits, Reading Habits, Fitness Habits and attributes like Universal and common outside of the Implementations object as shown in the expected json data?

The easiest way would be using Object.assign to merge the attributes.
//The Original Data
const Implementations = {
"Implementations": [
{
//Ignore
}
]
}
//The Attributes needed
const attributes = {
"UniversalOne": "",
"CommonOne": "",
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
const newData = Object.assign({}, Implementations, attributes);
console.dir(newData);
OR just add the data inside.
const Implementations = {
"Implementations": [
{
//Ignore
}
]
}
const newData = {
"UniversalOne": "",
"CommonOne": "",
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
newData.Implementations = Implementations.Implementations;
console.dir(newData);

Related

Processing array in JavaScript

So I have this javascript task, where I need to process data in an array. Suppose given array down below:
var data = [
/*Object 1*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/20191112172328535_1573550701898.jpeg"
],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 2*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 4*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 5*/
{
"personnelMateriaRel": [],
"videos": [
"/file/distribution/video"
],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 6*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/123.jpeg"
],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 7*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093345,
"longitude": 113.290808,
"time": "2020-01-02 20:25:18",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
]
This array contains objects. So For each object we have:
personnelMateriaRel; videos; contactor (which includes: id, mobile, name, otherTel2, temobile, workUnit); pics; distributionResult(which includes: latitude, longitude, time, content, address); sendTime
Here i have two objects Jack (ID=18320) and Mike (ID=31903), you can see that each object repeats for couple time. It's because they have different "time". So the task is, return new array (or other data structures) which contains the objects with the last "time" (i.e. the biggest "time" value) and merge all "pics" and "videos", all objects that have been deleted, with the object with biggest "time" value. So for above example, the correct value to be stored would be:
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/20191112172328535_1573550701898.jpeg" /*Merged*/
],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 7*/
{
"personnelMateriaRel": [],
"videos": [
"/file/distribution/video" /*Merged*/
],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/123.jpeg" /*Merged*/
],
"distributionResult": {
"latitude": 23.093345,
"longitude": 113.290808,
"time": "2020-01-02 20:25:18",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
}
Here what I've tried so far, but the result still not correct:
function resolve(array) {
let map = {}
let keys = ["personnelMateriaRel",
"videos", "pics", "distributionResult",
"sendTime"]
array.forEach(element => {
let id = element["contactor"]["id"]
let eleTime = element["distributionResult"]["time"]
let object = map[id]
if (!object) {
object = map[id] = {
id: id,
time: eleTime,
}
} else {
let lastTime = object["time"]
if (new Date(eleTime) <= new Date(lastTime)) {
object["time"] = lastTime
}
}
for (let value of keys) {
object[value] = object[value]
? object[value].concat(element[value])
: [].concat(element[value])
}
});
return Object.keys(map).map(id => map[id])
}
Would appreciate any help!
UPDATE
So thnx to (#thingEvery)'s answer, according to his code, i get the result down below:
The "time" field is correct, but i still get returned all objects who's "time" was less than the biggest "time". The image shown is for the first Object (i.e Jack). So there is 4 Jacks, and it seems all the fields (contactor, distributionResult, sendTime) getting merged. All i need to be merged is "pics" and "videos".
If I'm understanding your question correctly, you were almost there. All I had to do to make it work was add "contactor" to your list of keys and fix your time comparison.
var data = [
/*Object 1*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/20191112172328535_1573550701898.jpeg"
],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 2*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.095949110729155,
"longitude": 113.28544487112273,
"time": "2020-01-02 17:04:38",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 16:01:54"
},
/*Object 3*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 4*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 18320,
"mobile": "13705139529",
"name": "Jack",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.09594105827961,
"longitude": 113.28548480963536,
"time": "2020-01-02 17:34:27",
"content": "Arrived",
"address": "USA"
},
"sendTime": "2020-01-02 17:08:49"
},
/*Object 5*/
{
"personnelMateriaRel": [],
"videos": [
"/file/distribution/video"
],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 6*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [
"/file/distribution/123.jpeg"
],
"distributionResult": {
"latitude": 23.093305,
"longitude": 113.290806,
"time": "2020-01-02 20:25:03",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
/*Object 7*/
{
"personnelMateriaRel": [],
"videos": [],
"contactor": {
"id": 31903,
"mobile": "13924827229",
"name": "Mike",
"otherTel2": "",
"temobile": "",
"workUnit": ""
},
"pics": [],
"distributionResult": {
"latitude": 23.093345,
"longitude": 113.290808,
"time": "2020-01-02 20:25:18",
"content": "Arrived",
"address": "Canada"
},
"sendTime": null
},
]
function resolve(array) {
let map = {};
let keys = ["personnelMateriaRel", "videos", "pics"];
array.forEach(element => {
let id = element.contactor.id;
let eleTime = element.distributionResult.time;
let object = map[id]
if (!object) {
object = map[id] = {
contactor: element.contactor,
distributionResult: element.distributionResult,
sendTime: element.sendTime
}
} else {
let lastTime = object.distributionResult.time;
if (eleTime >= lastTime) {
object.contactor = element.contactor;
object.distributionResult = element.distributionResult;
object.distributionResult.time = eleTime;
object.sendTime = element.sendTime;
}
}
for (let value of keys) {
object[value] = object[value] ?
object[value].concat(element[value]) : [].concat(element[value])
}
});
return Object.keys(map).map(id => map[id])
}
console.log(resolve(data));

Attributes not showing up in json, restructure json objects

Original json data:
{
"UniversalOne": "",
"CommonOne": "",
"Implementations": [
{
"BirthDate": "",
"UniqueTraits": "",
"Male": {
"Gender": "Male",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": ""
},
"Female": {
"Gender": "Female",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": ""
},
"Country": [
{
"Orientation": "Male",
"Name": "ABCD",
"County": "East"
},
{
"Orientation": "Male",
"Name": "ABCD",
"County": "West"
},
{
"Orientation": "Female",
"Name": "EFGH",
"County": "East"
},
{
"Orientation": "Female",
"Name": "EFGH",
"County": "West"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
],
"Boy": [
{
"AgeGroup": "A",
"Id": 1,
"MaternalName": "",
"PaternalName": ""
},
{
"AgeGroup": "B",
"Id": 2,
"MaternalName": "",
"PaternalName": ""
},
{
"AgeGroup": "C",
"Id": 3,
"MaternalName": "",
"PaternalName": ""
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {},
"UniversalThree": "",
"CommonThree": ""
}
Expected json response:
{
"UniversalOne": "",
"CommonOne": "",
"Implementations": [
{
"BirthDate": "",
"UniqueTraits": "",
"Male": {
"Gender": "Male",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": "",
"Country": [
{
"Orientation": "Male",
"Name": "ABCD"
}
],
"EastCounty": {
"Orientation": "Male",
"Name": "ABCD",
"County": "East"
},
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": "",
"Country": [
{
"Orientation": "Female",
"Name": "EFGH"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"EastCounty": {
"Orientation": "Female",
"Name": "EFGH",
"County": "East"
},
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Girl": [
{
"AgeGroup": "A",
"identification": [
{
"Number": 1,
"MaternalName": "",
"PaternalName": ""
}
]
},
{
"AgeGroup": "B",
"identification": [
{
"Number": 1,
"MaternalName": "",
"PaternalName": ""
}
]
},
{
"AgeGroup": "C",
"identification": [
{
"Number": 1,
"MaternalName": "",
"PaternalName": ""
}
]
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {},
"UniversalThree": "",
"CommonThree": ""
}
Questions:
I have three specific questions:
1) How do I retain the attributes that are directly under "Male" and "Female" and also before "Male"? After I run my program these attributes are not shown in my response.
I want to retain attributes like
"BirthDate":"",
"UniqueTraits": "" AND
"Gender": "Male",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": ""
exactly as in my original and expected json data.
2) How do I add another EastCounty{} after Country[] both in Male and Female based on "County": East and Orientation? Please refer the original and expected json for reference.
3) How do I restructure Boy[] in original json to the new structure exactly as is shown in Girl[] in expected json response? Note "Id" in Boy[] changes to "Number" in Girl.So if there are multiple "identification" in either of the "AgeGroup" then "Number" would change sequentially for every record.
Current program:
function modifyImplementations(Implementations) {
var finalResult = [];
for (var i = 0; i < Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j = 0; j < currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
return finalResult
}
var x = Object.assign({}, Implementations);
x.Implementations = modifyImplementations(Implementations);
console.log(JSON.stringify(x));
This should be working function which would produce expected result, Please do some refactoring as certainly there are better ways to implement in few areas of code, just quickly done all your needs here to produce expected o/p and also your question needs to be updated with valid JSON's :
function modifyImplementations(Implementations) {
for (let i = 0; i < Implementations.Implementations.length; i++) {
let currentImplementation = Implementations.Implementations[i];
currentImplementation['Male']['Country'] = []
currentImplementation['Female']['Country'] = []
currentImplementation['Male']['EastCounty'] = []
currentImplementation['Female']['EastCounty'] = []
currentImplementation['Male']['State'] = currentImplementation['State'];
currentImplementation['Female']['State'] = currentImplementation['State'];
for (let j = 0; j < currentImplementation.Country.length; j++) {
let currentCountry = currentImplementation.Country[j];
let currentCountryObj = {}
if (currentCountry.Orientation === 'Male') {
if (currentCountry.County && currentCountry.County == "East") {
currentCountryObj['County'] = currentCountry.County
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Male']['EastCounty'].push(currentCountryObj)
} else {
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Male']['Country'].push(currentCountryObj);
}
} else if (currentCountry.Orientation === 'Female') {
if (currentCountry.County && currentCountry.County == "East") {
currentCountryObj['County'] = currentCountry.County
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Female']['EastCounty'].push(currentCountryObj)
} else {
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Female']['Country'].push(currentCountryObj);
}
}
}
delete currentImplementation['Country']
delete currentImplementation['State']
let mapObj = [];
for (items of currentImplementation.Boy) {
let objs = currentImplementation.Boy.filter((obj) => {
return items.AgeGroup === obj.AgeGroup
})
mapObj.push(objs)
currentImplementation.Boy = currentImplementation.Boy.filter(e => e.AgeGroup !== items.AgeGroup);
}
let finalArray = mapObj.filter(e => e.length > 0)
currentImplementation['Girl'] = []
for (anArray of finalArray) {
let finalObj = {}
finalObj.identification = [];
if (anArray.length && anArray.length > 1) {
let number = 1
for (oneObj of anArray) {
let objs = {};
objs['Number'] = number
objs['MaternalName'] = oneObj['MaternalName']
objs['PaternalName'] = oneObj['PaternalName']
number += 1
finalObj['AgeGroup'] = oneObj.AgeGroup
finalObj.identification.push(objs);
}
} else if (anArray.length == 1) {
let objs = {};
finalObj['AgeGroup'] = anArray[0].AgeGroup
objs = {};
objs['Number'] = 1
objs['MaternalName'] = anArray[0]['MaternalName']
objs['PaternalName'] = anArray[0]['PaternalName']
finalObj.identification.push(objs);
}
currentImplementation['Girl'].push(finalObj)
delete currentImplementation['Boy']
}
}
return Implementations
}

restructure json missing elements

Original json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Expected json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
"Country": [
{
"Orientation": "Male",
"Name": ABCD
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female"
"Country": [
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Program:
//Original JSON data in question.
var Implementations = {
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
// Program that make the conversion
var finalResult = [];
for (var i=0; i<Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j=0; j<currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
console.log(JSON.stringify(finalResult));
How do I add the objects like Personality Traits, Eating Habits, Reading Habits, Fitness Habits and attributes like Universal and common outside of the Implementations object in the current program?
If I am getting your question correctly, I think your code already gives you the expected JSON for Implementations property.
[
{
"Male": {
"Gender": "Male",
"Country": [
{
"Orientation": "Male",
"Name": "ABCD"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female",
"Country": [
{
"Orientation": "Female",
"Name": "EFGH"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
]
Therefore, if you are asking how to add the rest of the properties to achieve your expected JSON, you could just do this:
Implementations.Implementations = finalResult;
that will replace the original JSON implementations property to the one you have created.
Therefore say:
var Implementations = {
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
if you do Implementations.Implementations = filteredResult;
the Implementations will become:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male",
"Country": [
{
"Orientation": "Male",
"Name": "ABCD"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female",
"Country": [
{
"Orientation": "Female",
"Name": "EFGH"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Otherwise, explain a bit more of what you are trying to achieve.

How to transfer input box data to a complex structure JSON

I use jQuery get a JSON string from a API. I want to display it and change some field and PUT back to the API. But it seems to hard to gather information from input box and put it into right field.
Here is the json structure:
{
"economicStatus": "",
"title1": "",
"migrantEducation": "",
"disability": {
"status": "",
"section504Status": "",
"primaryDisability": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"awaitingInitialIDEAEvaluation": ""
},
"giftedTalented": "",
"firstNationalEnrollment": "",
"alertMessageList": [
{
"message": "object",
"messageType": ""
}
],
"medicalAlertMessageList": [
{
"message": "",
"severity": ""
}
],
"projectedGraduationYear": "",
"onTimeGraduationYear": "",
"graduationDate": "",
"economicDisadvantage": "",
"otherIdList": [
{
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
}
],
"name": {
"nameRole": "",
"actualNameOfRecord": {
"prefix": "",
"familyNameFirst": "",
"preferredFamilyNameFirst": "",
"givenName": "",
"middleName": "",
"familyName": "",
"preferredFamilyName": "",
"preferredGivenName": "",
"fullName": "",
"sortName": "",
"suffix": ""
}
},
"phoneNumberList": [
{
"number": "",
"extension": "",
"phoneNumberType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"listedStatus": ""
}
],
"emailList": [
{
"emailAddress": "",
"emailType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
}
],
"localId": {
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
},
"externalId": {
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
},
"addressRefIdList": [
{
"value": "",
"addressRole": ""
}
],
"otherNameList": [
{
"nameRole": "",
"otherName": {
"prefix": "",
"familyNameFirst": "",
"preferredFamilyNameFirst": "",
"givenName": "",
"middleName": "",
"familyName": "",
"preferredFamilyName": "",
"preferredGivenName": "",
"fullName": "",
"sortName": "",
"suffix": ""
}
}
],
"demographics": {
"birthDateVerification": "",
"sexus": "",
"birthDate": "",
"subregionOfBirth": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"stateProvinceOfBirth": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"placeOfBirth": "",
"countryOfBirth": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"countryArrivalDate": "",
"citizenshipStatus": "",
"languageProficiency": "",
"dwellingArrangement": "",
"maritalStatus": "",
"ethnicityList": [
{
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
],
"languageList": [
{
"languageCode": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"languageType": "",
"dialect": ""
}
],
"countryOfResidency": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"countryOfCitizenshipList": [
{
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
]
},
"electronicIdList": [
{
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
}
],
"refId": ""
}
And here is a sample data I get back from API, with some field are null:
{
"disability": null,
"economicStatus": null,
"migrantEducation": null,
"title1": null,
"alertMessageList": null,
"medicalAlertMessageList": null,
"projectedGraduationYear": null,
"onTimeGraduationYear": null,
"graduationDate": null,
"giftedTalented": null,
"economicDisadvantage": null,
"firstNationalEnrollment": null,
"otherIdList": [
{
"idType": {
"code": "AuthenticationUsername",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.OtherId"
},
"idValue": "ChK#username-60ty"
},
{
"idType": {
"code": "HMOF UserName",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.OtherId"
},
"idValue": "ChK#username-60ty.arda.stu"
},
{
"idType": {
"code": "Role",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.OtherId"
},
"idValue": "learner"
}
],
"addressRefIdList": null,
"name": null,
"localId": {
"idType": {
"code": "LASID",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.LocalId"
},
"idValue": "79800003270ABCKrtg12"
},
"externalId": {
"idType": {
"code": "SASID",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.ExternalId"
},
"idValue": "NULL"
},
"electronicIdList": null,
"otherNameList": null,
"demographics": null,
"phoneNumberList": null,
"emailList": null,
"refId": "3329962f-18ab-415f-addb-132cbe613d68"
}
Is there a simple way to change the fields in a page using input box? I try to create as many input boxes as needed and name them and associate them with corresponding JSON field... But it seems to tedious and can not update array dynamically.

comparing Two array in angularJs

I have two arrays like this :
var friendemail = [ {
"data": {
"status": "OK",
"message": "User list fetched successfully",
"userList": [
{
"userId": 1,
"emailId": "abc.com",
"firstName": "Abc",
"lastName": "Xyz",
"nickName": "Nic",
"type": "USER",
"apiKey": "355901361"
},
{
"userId": 2,
"emailId": "babitadhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 3,
"emailId": "testuser#g.com",
"firstName": "Test_User",
"lastName": "Account",
"nickName": "Testi",
"type": "USER",
"apiKey": "1403626362113"
},
{
"userId": 4,
"emailId": "dhami#gmail.com",
"firstName": "dhami",
"lastName": "Dhami",
"nickName": "bobby",
"type": "DEVELOPER",
"apiKey": "222234567"
},
{
"userId": 5,
"emailId": "babita.dhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "1403709178117"
},
{
"userId": 6,
"emailId": "Chris#abc.com",
"firstName": "dhami",
"lastName": "dhami",
"nickName": "dhami",
"type": "DEVELOPER",
"apiKey": "333234567"
},
{
"userId": 7,
"emailId": "kevin.wei#qdevinc.com",
"firstName": "abc",
"lastName": "xyz",
"nickName": "none",
"type": "DEVELOPER",
"apiKey": "111234567"
},
{
"userId": 8,
"emailId": "dhamji#gmail.com",
"firstName": "Bab",
"lastName": "Dham",
"nickName": "bobby",
"type": "USER",
"apiKey": "1403790266057"
},
{
"userId": 9,
"emailId": "info#hemlockhills.ca",
"firstName": "Jenn",
"lastName": "Becker",
"nickName": "JennB",
"type": "USER",
"apiKey": "355901361"
},
{
"userId": 10,
"emailId": "babitadhami1#gmail.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 11,
"emailId": "b.dhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 12,
"emailId": "dhami.babita#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 13,
"emailId": "Francie#abc.com",
"firstName": "Francie",
"lastName": "Francie",
"nickName": "Francie",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 14,
"emailId": "Sam#abc.com",
"firstName": "Sam",
"lastName": "M",
"nickName": "S",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 15,
"emailId": "Sid#abc.com",
"firstName": "Sid",
"lastName": "B",
"nickName": "S",
"type": "USER",
"apiKey": "22234567"
},
{
"userId": 16,
"emailId": "tim#outlook.com",
"firstName": "tim",
"lastName": "tim",
"nickName": "tim",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 17,
"emailId": "racing#gmail.com",
"firstName": "racing",
"lastName": "racing",
"nickName": "Hollywood",
"type": "USER",
"apiKey": "222234567"
}
]
},
"status": 200,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "OK"
}]
and another is
var deviceContactEmail = [
{
"id": "1",
"rawId": "1",
"displayName": "kandwal",
"name": {
"formatted": "kandwal",
"givenName": "kandwal"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "testuser#g.com",
"id": "6",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/1/photo",
"type": "url",
"id": "1",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "2",
"rawId": "2",
"displayName": "xyz",
"name": {
"formatted": "xyz ",
"givenName": "xyz"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "Chris#abc.com",
"id": "12",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/2/photo",
"type": "url",
"id": "7",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "3",
"rawId": "3",
"displayName": "cdf",
"name": {
"formatted": "cdf",
"givenName": "cdf"
},
"nickname": null,
"phoneNumbers": null,
"emails": null,
"addresses": [
{
"region": "Uk",
"id": "19",
"locality": "Dehra Dun",
"formatted": "dddd",
"type": "home",
"pref": false,
"country": "India"
}
],
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/3/photo",
"type": "url",
"id": "14",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "4",
"rawId": "4",
"displayName": "abcd",
"name": {
"formatted": "scd ",
"givenName": "scd"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "dhami#gmail.com",
"id": "26",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/4/photo",
"type": "url",
"id": "21",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "5",
"rawId": "5",
"displayName": "hiteshbhattcse#gmail.com",
"name": {
"formatted": "hiteshbhattcse#gmail.com ",
"givenName": "hiteshbhattcse#gmail.com"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "hiteshbhattcse#gmail.com",
"id": "33",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/5/photo",
"type": "url",
"id": "28",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "6",
"rawId": "6",
"displayName": "hitet#gmail.com",
"name": {
"formatted": "hitet#gmail.com ",
"givenName": "hitet#gmail.com"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "hiteshbhatt#gmail.com",
"id": "40",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/6/photo",
"type": "url",
"id": "35",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "7",
"rawId": "7",
"displayName": null,
"name": {
"formatted": ""
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "mayank.th088#gmail.com",
"id": "46",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/7/photo",
"type": "url",
"id": "41",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "8",
"rawId": "8",
"displayName": null,
"name": {
"formatted": ""
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "gcjoshi83#gmail.com",
"id": "53",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/8/photo",
"type": "url",
"id": "48",
"pref": false
}
],
"categories": null,
"urls": null
}]
I want to compare both of them for email id . and wanna get the common email id inside 1 array and rest in one array from deviceContactEmail.
I tried angular. each but not getting success.
var wUser = [];
var nonWUser = [];
angular.forEach(deviceContactEmail, function(phonevalue){
console.log(phonevalue);
angular.forEach(friendemail, function(value){
if (phonevalue.emails) {
if(phonevalue.emails[0].value === value.emailId){
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
}else{
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
nonWUser.push(phonevalue);
};
}
})
})
Hi Try this I solved to remove the duplicates value in the array check it...
var wUser = [];
var nonWUser = [];
angular.forEach(deviceContactEmail, function(phonevalue){
console.log(phonevalue);
angular.forEach(friendemail[0].data.userList, function (value) {
if (phonevalue.emails) {
if(phonevalue.emails[0].value === value.emailId){
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
}
else {
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
if ($scope.nonWUser.length == 0) {
nonWUser.push(phonevalue);
}
var filteredVal= $scope.nonWUser.filter(function (filterValue) {
return filterValue.emails[0].value == phonevalue.emails[0].value;
});
if (filteredVal.length == 0)
nonWUser.push(phonevalue);
}
}
});
});
check the edited file
It seem you are not pointing the inner loop at the right list. friendemail is a list but contains only one item. I assume the emailId you are testing for is buried inside the data which happens to be child of friendemail. Try the code below
angular.forEach(deviceContactEmail, function(phonevalue) {
console.log("................ ",phonevalue, " ", friendemail[0].data.userList.length);
angular.forEach(friendemail[0].data.userList, function(value) {
if (phonevalue.emails) {
if (phonevalue.emails[0].value === value.emailId) {
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
} else {
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
nonWUser.push(phonevalue);
}
;
}
})
})

Categories