Processing array in JavaScript - 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));

Related

Microsoft Graph Api - Appointment Bookings dateTime Issue

So i've been using the microsoft bookings Beta Api getting the List from this URL:
GET https://graph.microsoft.com/beta/bookingBusinesses/Contosolunchdelivery#M365B489948.onmicrosoft.com/appointments
it works fine except i need to get the start -> dateTime and end -> dateTime for the specific appointment but its returning wrong start dates? even though when i go to bookings i clearly put the start time.
This is what the JSON-Example should looks like:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#bookingBusinesses('Contosolunchdelivery%40M365B489948.onmicrosoft.com')/appointments",
"value": [
{
"id": "AAMkADKoAAA=",
"selfServiceAppointmentId": "00000000-0000-0000-0000-000000000000",
"customerId": "829e3cb5-3d4d-4319-a8de-1953aedaa166",
"customerName": "Bob Kelly",
"customerEmailAddress": "bobk#tailspintoys.com",
"customerPhone": "213-555-0108",
"customerNotes": null,
"serviceId": "57da6774-a087-4d69-b0e6-6fb82c339976",
"serviceName": "Catered bento",
"duration": "PT30M",
"preBuffer": "PT5M",
"postBuffer": "PT10M",
"priceType": "fixedPrice",
"price": 10,
"serviceNotes": null,
"optOutOfCustomerEmail": false,
"staffMemberIds": [],
"invoiceAmount": 10,
"invoiceId": "1002",
"invoiceStatus": "open",
"invoiceUrl": "theInvoiceUrl",
"customerLocation": {
"displayName": "Customer",
"locationEmailAddress": null,
"locationUri": "",
"locationType": null,
"uniqueId": null,
"uniqueIdType": null,
"address": {
"type": "home",
"postOfficeBox": "",
"street": "",
"city": "",
"state": "",
"countryOrRegion": "",
"postalCode": ""
},
"coordinates": {
"altitude": null,
"latitude": null,
"longitude": null,
"accuracy": null,
"altitudeAccuracy": null
}
},
"start": {
"dateTime": "2018-04-30T13:00:00.0000000Z",
"timeZone": "UTC"
},
"end": {
"dateTime": "2018-04-30T13:30:00.0000000Z",
"timeZone": "UTC"
},
"serviceLocation": {
"displayName": "Customer location (987 Third Avenue, Buffalo, NY 98052, USA)",
"locationEmailAddress": null,
"locationUri": "",
"locationType": null,
"uniqueId": null,
"uniqueIdType": null,
"address": {
"type": "home",
"postOfficeBox": "",
"street": "",
"city": "",
"state": "",
"countryOrRegion": "",
"postalCode": ""
},
"coordinates": {
"altitude": null,
"latitude": null,
"longitude": null,
"accuracy": null,
"altitudeAccuracy": null
}
},
"reminders": [],
"invoiceDate": {
"dateTime": "2018-04-30T13:30:00.0000000Z",
"timeZone": "UTC"
}
},
{
"id": "AAMkADKnAAA=",
"selfServiceAppointmentId": "00000000-0000-0000-0000-000000000000",
"customerId": "7ed53fa5-9ef2-4f2f-975b-27447440bc09",
"customerName": "Jordan Miller",
"customerEmailAddress": "jordanm#contoso.com",
"customerPhone": "213-555-0199",
"customerNotes": null,
"serviceId": "57da6774-a087-4d69-b0e6-6fb82c339976",
"serviceName": "Catered bento",
"duration": "PT30M",
"preBuffer": "PT5M",
"postBuffer": "PT10M",
"priceType": "fixedPrice",
"price": 10,
"serviceNotes": null,
"optOutOfCustomerEmail": false,
"staffMemberIds": [],
"invoiceAmount": 10,
"invoiceId": "1001",
"invoiceStatus": "open",
"invoiceUrl": "theInvoiceUrl",
"customerLocation": {
"displayName": "Customer",
"locationEmailAddress": null,
"locationUri": "",
"locationType": null,
"uniqueId": null,
"uniqueIdType": null,
"address": {
"type": "home",
"postOfficeBox": "",
"street": "",
"city": "",
"state": "",
"countryOrRegion": "",
"postalCode": ""
},
"coordinates": {
"altitude": null,
"latitude": null,
"longitude": null,
"accuracy": null,
"altitudeAccuracy": null
}
},
"start": {
"dateTime": "2018-05-01T12:00:00.0000000Z",
"timeZone": "UTC"
},
"end": {
"dateTime": "2018-05-01T12:30:00.0000000Z",
"timeZone": "UTC"
},
"serviceLocation": {
"displayName": "Customer location (123 First Avenue, Buffalo, NY 98052, USA)",
"locationEmailAddress": null,
"locationUri": "",
"locationType": null,
"uniqueId": null,
"uniqueIdType": null,
"address": {
"type": "home",
"postOfficeBox": "",
"street": "",
"city": "",
"state": "",
"countryOrRegion": "",
"postalCode": ""
},
"coordinates": {
"altitude": null,
"latitude": null,
"longitude": null,
"accuracy": null,
"altitudeAccuracy": null
}
},
"reminders": [],
"invoiceDate": {
"dateTime": "2018-05-01T12:30:00.0000000Z",
"timeZone": "UTC"
}
}
]
}
And this is what im getting for the start and end date time:
start:
dateTime: "0001-01-01T00:00:00.0000000Z"
timeZone: "Etc/UTC"
end:
dateTime: "0001-01-01T00:00:00.0000000Z"
timeZone: "Etc/UTC"
I dont know what i'm doing wrong, i'd appreciate any help.
So for some reason using this URL:
GET /bookingBusinesses/{id}/calendarView?start={start-value}&end={end-value}
did end up giving me the exact results i was looking with correct time and everything the list appointments url was giving me.
I guess that's why this is still in BETA

Rearrange json with sample data

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);

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.

Use Javascript object variable for an if statement

I'm using javascript to display information of a shop basket. I know how to pull the data and create elements from it, but I need to use one of the variables for an if statement, and am unsure how to.
If this is true: "isPunchOut": false, then I want to target that with jQuery, and do something like $(".button").remove();
How do I do this?
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"isPunchOut": false,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"shippingFormatSum": "\u20AC0",
"orderno": "0",
"orderFormatSum": "\u20AC130",
"voucher": "",
"orderFormatVat": "\u20AC27,30",
"currencySymbol": "\u20AC",
"currency": "EUR",
"orderVat": 27.3,
"orderSum": 130.0,
"items": [{
"imageURI": "\/imgr\/8c82380c-65f5-43aa-83ad-fae1215b5b39\/70\/70",
"qtyAvail": 7,
"price": 130.0,
"qty": 1,
"artno": "D630-T7100-GE-REF",
"vat": 27.3,
"formatVat": "\u20AC27,30",
"id": "52307",
"label": "D630 C2D-T7100/2GB/80GB/DVD/14"/NO COA WLAN",
"category": "Computers - Notebooks",
"formatPrice": "\u20AC130",
"manufacturer": "Dell"
}]
}
}
You can take a look at below JS code for reference:
var isPunchOut = retailerData["user"]["isPunchOut"];
if(isPunchOut === false)
$(".button").remove();
I would say you should try some code first and put where you get stuck .We not here to write code for your problems.
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"isPunchOut": false,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"shippingFormatSum": "\u20AC0",
"orderno": "0",
"orderFormatSum": "\u20AC130",
"voucher": "",
"orderFormatVat": "\u20AC27,30",
"currencySymbol": "\u20AC",
"currency": "EUR",
"orderVat": 27.3,
"orderSum": 130.0,
"items": [{
"imageURI": "\/imgr\/8c82380c-65f5-43aa-83ad-fae1215b5b39\/70\/70",
"qtyAvail": 7,
"price": 130.0,
"qty": 1,
"artno": "D630-T7100-GE-REF",
"vat": 27.3,
"formatVat": "\u20AC27,30",
"id": "52307",
"label": "D630 C2D-T7100/2GB/80GB/DVD/14"/NO COA WLAN",
"category": "Computers - Notebooks",
"formatPrice": "\u20AC130",
"manufacturer": "Dell"
}]
}
}
if(retailerData.user.isPunchOut){
//your jquery operation
}
Checkjsfiddle
What about?
if (!retailerData.user.isPunchOut) {
$(".button").remove();
}

JSON Object Transformation into specific Javascript Array or JSON Object

So I have this JSON Object. Let's call it var dataFetched
var dataFetched = {
"status": "ok",
"count": 4,
"count_total": 4,
"pages": 1,
"posts": [
{
"id": 57,
"type": "keyword",
"slug": "crime-scene-investigation-csi",
"url": "http://keyjargon.com/keyword/crime-scene-investigation-csi/",
"status": "publish",
"title": "Crime Scene Investigation (CSI)",
"title_plain": "Crime Scene Investigation (CSI)",
"content": "",
"excerpt": "",
"date": "2015-11-07 05:01:51",
"modified": "2015-11-07 05:01:51",
"categories": [
{
"id": 8,
"slug": "law",
"title": "Law",
"description": "",
"parent": 0,
"post_count": 1
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
},
{
"id": 50,
"type": "keyword",
"slug": "fx",
"url": "http://keyjargon.com/keyword/fx/",
"status": "publish",
"title": "FX",
"title_plain": "FX",
"content": "",
"excerpt": "",
"date": "2015-11-05 10:07:17",
"modified": "2015-11-05 10:22:10",
"categories": [
{
"id": 3,
"slug": "business",
"title": "Business",
"description": "",
"parent": 0,
"post_count": 2
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
},
{
"id": 48,
"type": "keyword",
"slug": "common-core",
"url": "http://keyjargon.com/keyword/common-core/",
"status": "publish",
"title": "Common CORE",
"title_plain": "Common CORE",
"content": "",
"excerpt": "",
"date": "2015-11-05 10:06:40",
"modified": "2015-11-07 04:58:06",
"categories": [
{
"id": 2,
"slug": "technology",
"title": "Technology",
"description": "",
"parent": 0,
"post_count": 3
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
},
{
"id": 46,
"type": "keyword",
"slug": "api",
"url": "http://keyjargon.com/keyword/api/",
"status": "publish",
"title": "API",
"title_plain": "API",
"content": "",
"excerpt": "",
"date": "2015-11-05 10:06:19",
"modified": "2015-11-05 10:21:47",
"categories": [
{
"id": 2,
"slug": "technology",
"title": "Technology",
"description": "",
"parent": 0,
"post_count": 3
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
}
]
}
I want to rearrange this result to link the Category title :
dataFetched.posts[i].categories[0].title
to the Post title :
dataFetched.post[i].title
so that each category displays all the posts titles related to it. I want my object (whether multi-demmensional array or another object) to be able to retrieve all the Posts titles related to the category.
Maybe something like this :
[Category1: {Post_titleA, PostTitleB, PostTitleC}, Category2: {PostTileF, PostTileX}, etc ] where each category can retrieve all its posts.( The format does not matter as long the Object with Category title X can retrieve all posts titles that belong to it ).
How do I do this in Javascript ? The result variable is not static but its format is the same as the one posted here.
This is what I tried so far.
// Function to sort unique values of an array
function sort_unique(arr) {
arr = arr.sort(function (a, b) { return a*1 - b*1; });
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
if (arr[i-1] !== arr[i]) {
ret.push(arr[i]);
}
}
return ret;
}
//Define two arrays to be used for categories and Keywords
var keywords = [];
var industries = [];
//Fill up the categories(Industries) array and the keywords one
for ( var i = 0, iLen = dataFetched.count; i < iLen; i++) {
keywords[i] = dataFetched.posts[i].title;
industries[i] = dataFetched.posts[i].categories[0].title;
}
// Sort and eliminate duplication of category and keyword names
keywords = sort_unique(keywords);
industries = sort_unique(industries);
// Now time for trouble: Define a multi-dimmensional array that links each category/industry to its keywords **This is where I AM STUCK**
ind = new Array;
for(i=0; i<industries.length;i++){
ind[i] = new Array;
}
for(i=0;i<dataFetched.count;i++){
ind[i][0]= dataFetched.posts[i].categories[0].title;
for(j=0;j<dataFetched.count;j++){
var count = ind[i].length;
if(ind[i][0] == dataFetched.posts[j].categories[0].title){
ind[i][count] = dataFetched.posts[j].title;
}
}
}
It is possible to create object with categories. As a result all entries can be accessed by category name and you do not need to sort them to have unique titles:
var posts = dataFetched.posts;
var cat = {};
posts.forEach(
function(p) {
p.categories.forEach(
function(c) {
if (!cat[c.title])
cat[c.title] = [];
cat[c.title].push(p.title);
});
});
console.log(cat);
Output for your example:
Object {Law: Array[1], Business: Array[1], Technology: Array[2]}
Each category title is a key in this object and the arrays of posts are values of those keys.
The output example you showed is wrong, in JS there's no object like
[Category1: {Post_titleA, PostTitleB, PostTitleC}, Category2: {PostTileF, PostTileX}, etc ]
The most similar thing you can get is a JSON object like this:
{
"Category1" : ["Post_titleA", "PostTitleB", "PostTitleC"],
"Category2" : ["PostTileF", "PostTileX"],
//etc..
}
In order to achieve this, you can use the following function:
function getTitlesByCategory (json) {
var result = {}
json.posts.map(function (post) {
post.categories.map(function (category) {
result[category.title] = result[category.title] || [];
result[category.title].push(post.title);
});
});
return result;
}

Categories