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.
Related
I am getting an array of objects from the server in the following format:
[
{
"country": "UK",
"name": "Battery Ltd 1",
"type": "contact"
},
{
"country": "USA",
"name": "Technologies Inc. 1",
"type": "contact"
},
{
"country": "",
"name": "Jayne Mansfield",
"type": "representative"
},
{
"country": "China",
"name": "Technologies Inc. 2",
"type": "contact"
},
{
"country": "",
"name": "Dan Borrington",
"type": "representative"
},
{
"country": "",
"name": "Susan Reedy",
"type": "representative"
}
]
However, I need to iterate over this array of objects and convert it to this format: I want to combine the CONTACT type with the following REPRESENTATIVE object or objects. That is, at the output, I would like to get such an array with arrays:
[
[
{
"country": "UK",
"name": "Battery Ltd 1",
"type": "contact"
}
],
[
{
"country": "USA",
"name": "Technologies Inc. 1",
"type": "contact"
},
{
"country": "",
"name": "Jayne Mansfield",
"type": "representative"
},
],
[
{
"country": "China",
"name": "Technologies Inc. 2",
"type": "contact"
},
{
"country": "",
"name": "Dan Borrington",
"type": "representative"
},
{
"country": "",
"name": "Susan Reedy",
"type": "representative"
}
]
]
You can go through the elements and create a group if element is a contact, and add to the group otherwise:
const data = [
{
"country": "UK",
"name": "Battery Ltd 1",
"type": "contact"
},
{
"country": "USA",
"name": "Technologies Inc. 1",
"type": "contact"
},
{
"country": "",
"name": "Jayne Mansfield",
"type": "representative"
},
{
"country": "China",
"name": "Technologies Inc. 2",
"type": "contact"
},
{
"country": "",
"name": "Dan Borrington",
"type": "representative"
},
{
"country": "",
"name": "Susan Reedy",
"type": "representative"
}
]
const result = data.reduce( (r, e) => (e.type === 'contact' ? r.push([e]) : r[r.length -1].push(e), r), [])
console.log(result)
const array = []
let current = []
let hasRepresentative = false
for (const item of getItems()) {
if (current.length === 0) {
current.push(item)
continue
}
if (hasRepresentative && item.type === 'contact') {
array.push(current)
current = [item]
continue
}
current.push(item)
hasRepresentative = true
}
array.push(current)
console.log(array)
function getItems() { return [
{
"country": "UK",
"name": "Battery Ltd 1",
"type": "contact"
},
{
"country": "USA",
"name": "Technologies Inc. 1",
"type": "contact"
},
{
"country": "",
"name": "Jayne Mansfield",
"type": "representative"
},
{
"country": "China",
"name": "Technologies Inc. 2",
"type": "contact"
},
{
"country": "",
"name": "Dan Borrington",
"type": "representative"
},
{
"country": "",
"name": "Susan Reedy",
"type": "representative"
}
]
}
I am new to node.js and javascript. I am trying to build a rest API.
For a specific purpose, I need to convert an object to 3d array.
I tried running for, foreach loop but it is not providing what I am trying to achieve.
My object looks like this.
"data": [
{
"id": 15184,
"badge_id": "330886",
"name": "Rukmani J. Solanki",
"gender": "Female",
"type": "PF",
"department": "Sales",
"checkin": "2021-09-24T08:52:44.000Z",
"checkout": "2021-09-24T08:57:45.000Z",
"hours": "00:05"
},
{
"id": 15185,
"badge_id": "440886",
"name": "Jairam J. Solanki",
"gender": "Male",
"type": "PM",
"department": "Sales",
"checkin": "2021-09-24T09:28:32.000Z",
"checkout": null,
"hours": null
}
]
And I want something like this
{
"onfield": [
{
"key": "Sales",
"data": {
"PM": [
{
"name": "Gokuldas S. Sundrani",
"badge_id": "441101",
"gender": "Male",
"checkIn": "2021-09-24 06:04:18",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "551249",
"gender": "Male",
"checkIn": "2021-09-24 06:47:31",
"checkOut": "2021-09-24 08:32:00",
"hours": "1.7 Hours"
},
{
"name": "Praveen N. Jethwani",
"badge_id": "771328",
"gender": "Male",
"checkIn": "2021-09-24 07:14:11",
"checkOut": "2021-09-24 08:29:34",
"hours": "1.3 Hours"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "88249",
"gender": "Male",
"checkIn": "2021-09-24 08:32:00",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Arjundas D. Chhabra",
"badge_id": "661248",
"gender": "Male",
"checkIn": "2021-09-24 10:19:22",
"checkOut": "2021-09-24 18:38:32",
"hours": "8.3 Hours"
},
{
"name": "Parmanand C. Lalwani",
"badge_id": "8651418",
"gender": "Male",
"checkIn": "2021-09-24 14:51:08",
"checkOut": "2021-09-24 17:39:27",
"hours": "2.8 Hours"
},
{
"name": "Dhanalal G. Chouhan",
"badge_id": "5501392",
"gender": "Male",
"checkIn": "2021-09-24 14:58:46",
"checkOut": "2021-09-24 18:20:50",
"hours": "3.4 Hours"
}
],
"PF": [
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "501993",
"gender": "Female",
"checkIn": "2021-09-24 06:47:48",
"checkOut": "2021-09-24 08:32:12",
"hours": "1.7 Hours"
},
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "801993",
"gender": "Female",
"checkIn": "2021-09-24 08:32:12",
"checkOut": null,
"hours": "NoCheckOut"
}
],
"OM": [
{
"name": "Yadvendra Bhati",
"badge_id": "2255454",
"gender": "male",
"checkIn": "2021-09-24 13:38:37",
"checkOut": "2021-09-24 17:24:11",
"hours": "3.8 Hours"
}
],
"OF": [
{
"name": "Yashoda Bhati",
"badge_id": "223F0029",
"gender": "Female",
"checkIn": "2021-09-24 13:38:44",
"checkOut": "2021-09-24 17:24:25",
"hours": "3.8 Hours"
}
]
}
}
]
}
How can this be done?
I will be really grateful to you for your help.
I have googled and searched StackOverflow but did not find anything which deals with this kind of problem.
Thank You
Although I totally agree with Juan Mendes, here is a tip in order for you to be able to accomplish this. You may get an intermediate form for your data as this one:
{
"onfield": [
{
"key": "dept1",
"data": {
"PM": [
{
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male"
}
]
}
},
{
"key": "dept2",
"data": {
"PF": [
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female"
}
]
}
},
{
"key": "dept1",
"data": {
"PM": [
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}
]
}
}
]
}
Perhaps transforming your source data to this one is easier. And getting to your target from here will be just a matter of merging arrays of the same type.
Do not hesitate to ask if this keeps being difficult. But as said, please try to solve this yourself, that's the way you are going to learn.
let data = [{ "id": 123, "badge_id": "1231", "name": "name1", "gender": "Male", "type": "PM", "dept": "dept1" }, { "id": 124, "badge_id": "1232", "name": "name2", "gender": "Female", "type": "PF", "dept": "dept2" }, { "id": 125, "badge_id": "1233", "name": "name3", "gender": "Male", "type": "PM", "dept": "dept1" }];
let Report = []
data.forEach((item) => {
let obj = Report.find(v => v.dept == item.dept);
if (!obj) Report.push(obj = {
dept: item.dept,
type: {}
});
obj.type[item.type] ??= [];
obj.type[item.type].push({
id: item.id,
badge_id: item.badge_id,
name: item.name,
gender: item.gender,
});
})
console.log(Report)
Here's Something i think is more feasible than your result .. Checkout
let myObject = {
"data": [ {
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male",
"type": "PM",
"dept": "dept1"
},
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female",
"type": "PF",
"dept": "dept2"
},
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}]
}
function generateReport(object) {
let obj = {
"Report": []
};
let types = [];
object.data.forEach(arr =>{
if(!types.includes(arr.type)){
types.push(arr.type);
}
});
types.forEach(type =>{
obj.Report.push({
type : type,
users : object.data.filter(arr=>{ let a = arr.type == type;
if(a){
delete arr.type;
}
return a;
})
});
});
return obj;
}
myObject = generateReport(myObject);
console.log(myObject)
You oculd take the wanted grouping keys in an array and destructure the object to remove this keys from the object.
Every key takes it own nested object structure.
const
data = [{ id: 123, badge_id: "1231", name: "name1", gender: "Male", type: "PM", dept: "dept1" }, { id: 124, badge_id: "1232", name: "name2", gender: "Female", type: "PF", dept: "dept2" }, { id: 125, badge_id: "1233", name: "name3", gender: "Male", type: "PM", dept: "dept1" }],
keys = ['dept', 'type'],
result = data
.reduce((r, o) => {
keys
.reduce(function (t, k) {
let key;
({ [k]: key, ...o } = o);
if (!t[key]) t._.push({ [k]: key, data: (t[key] = { _: [] })._ });
return t[key];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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
}
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);
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);
}
;
}
})
})