Best way to transform data - javascript

I have a vendor API call in my nodejs app that returns various objects, with the below being an example of one object in the the JSON:
[{
"id": 365467865567,
"type": "PERSON",
"created_time": 1492809120,
"updated_time": 1492809542,
"last_contacted": 1492809128,
"properties": [
{
"type": "SYSTEM",
"name": "phone",
"value": "123456789"
},
{
"type": "SYSTEM",
"name": "first_name",
"value": "Test2"
},
{
"type": "SYSTEM",
"name": "last_name",
"value": "You"
},
{
"type": "CUSTOM",
"name": "utm_medium",
"value": "email"
}
]
}]
Its not very easy to use the data in this format, and need to transpose it to a key,value format. Something similar to:
[{
"id": 365467865567,
"type": "PERSON",
"created_time": 1492809120,
"updated_time": 1492809542,
"last_contacted": 1492809128,
"properties":
{
"phone": "123456789",
"first_name": "Test2",
"last_name": "You",
"utm_medium": "email"
}
}]
What would be the most efficient way to transform this?

Try looping over the properties and reassigning the variable.
var array = [{
"id": 365467865567,
"type": "PERSON",
"created_time": 1492809120,
"updated_time": 1492809542,
"last_contacted": 1492809128,
"properties": [{
"type": "SYSTEM",
"name": "phone",
"value": "123456789"
}, {
"type": "SYSTEM",
"name": "first_name",
"value": "Test2"
}, {
"type": "SYSTEM",
"name": "last_name",
"value": "You"
}, {
"type": "CUSTOM",
"name": "utm_medium",
"value": "email"
}]
}];
array.forEach(function(obj) {
var properties = {};
obj.properties.forEach(function(prop) {
properties[prop.name] = prop.value;
});
obj.properties = properties;
});
https://jsfiddle.net/hycg5r80/3/

here's a way, idk if most efficient but it's short n sweet.
thing[0].properties = thing[0].properties.reduce( (p, n) => (
n[p.name] = p.value;
return n;
), {});

Related

JS: merging 2 arrays within an object

Given a JSON object, how would you merge the batter array and topping array within the object. I know I can do let x = foo.batters.batter.concat(foo.topping), which will give me an array of the merged array but what if I wanted it within object?
foo = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
Your answer is partially true. But you didn't add the value to the foo object.
You can do it like this:
foo.mergedArray = foo.batters.batter.concat(foo.topping);
After that, when you call foo.mergedArray you can access merged array of batter and topping.
If one of the batter and topping has changed foo.mergedArray will not be updated. Because foo.mergedArray has its own referance.
Try this:
foo.batters.batter = [...foo.batters.batter, ...foo.topping];

Sorting Node's on the base of parent-Id [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 2 years ago.
Want to sort my data all node come first before calling its parent node
[
{
"id": 7832454551,
"name": "usr",
"type": "DIRECTORY"
},
{
"id": 7832454554,
"name": "applications",
"type": "DIRECTORY",
"parentId": 7832454553
},
{
"id": 7832454555,
"name": "mimeinfo.cache",
"type": "FILE",
"parentId": 7832454554
},
{
"id": 7832454553,
"name": "share",
"type": "DIRECTORY",
"parentId": 7832454552
},
{
"id": 7832454552,
"name": "local",
"type": "DIRECTORY",
"parentId": 7832454551
}
]
want to update data like this using javascript
[
{
"id": 7832454551,
"name": "usr",
"type": "DIRECTORY"
},
{
"id": 7832454552,
"name": "local",
"type": "DIRECTORY",
"parentId": 7832454551
},
{
"id": 7832454553,
"name": "share",
"type": "DIRECTORY",
"parentId": 7832454552
},
{
"id": 7832454554,
"name": "applications",
"type": "DIRECTORY",
"parentId": 7832454553
},
{
"id": 7832454555,
"name": "mimeinfo.cache",
"type": "FILE",
"parentId": 7832454554
}
]
try this one
const sortedData = [
{
"id": 7832454551,
"name": "usr",
"type": "DIRECTORY"
},
{
"id": 7832454554,
"name": "applications",
"type": "DIRECTORY",
"parentId": 7832454553
},
{
"id": 7832454555,
"name": "mimeinfo.cache",
"type": "FILE",
"parentId": 7832454554
},
{
"id": 7832454553,
"name": "share",
"type": "DIRECTORY",
"parentId": 7832454552
},
{
"id": 7832454552,
"name": "local",
"type": "DIRECTORY",
"parentId": 7832454551
}
].sort(function(a,b){
if(a.parentId!= undefined && b.parentId != undefined){
return a.parentId > b.parentId
}
return false;
});
console.log(sortedData);

Get the distinct object from the array of objects in Typescript Angular 8

I have an array of object as shown below:
[{
"name": "Okta Verify Push",
"provider": "OKTA",
"type": "push",
"status": 0,
"id": "opfhgfgaidhyBw2H90h7"
}, {
"name": "Okta Verify TOTP",
"provider": "OKTA",
"type": "token:software:totp",
"status": 0,
"id": "osthgek5jmWTckcka0h7"
}, {
"name": "Unknown",
"provider": "CUSTOM",
"type": "claims_provider",
"status": 1,
"id": "clpn4wdtqtH6geILD0h7"
}, {
"name": "Google Authenticator",
"provider": "GOOGLE",
"type": "token:software:totp",
"status": 1,
"id": null
}]
I want to get the distinct object as array based on the **provider**
I tried
[...new Set(item.filter(factor => factor.status == MultiFactorAuthenticationEnrolmentStatus.Enrolled).map(factor => factor.provider))];
This returns string of array such as ["GOOGLE", "OKTA","CUSTOM"]
My requirement is to get the Array of Object such as
[{
"name": "Okta Verify Push",
"provider": "OKTA",
"type": "push",
"status": 0,
"id": "opfhgfgaidhyBw2H90h7"
}, {
"name": "Unknown",
"provider": "CUSTOM",
"type": "claims_provider",
"status": 1,
"id": "clpn4wdtqtH6geILD0h7"
}, {
"name": "Google Authenticator",
"provider": "GOOGLE",
"type": "token:software:totp",
"status": 1,
"id": null
}]
Reference - How to get distinct values from an array of objects in JavaScript?
In the case that you have a preference for taking the first occurrence, you can first map the data into an object based on provider being the key and itself as the value. Once that is done, you can then extract the all of the values with Object#values.
const data = [{
"name": "Okta Verify Push",
"provider": "OKTA",
"type": "push",
"status": 0,
"id": "opfhgfgaidhyBw2H90h7"
}, {
"name": "Okta Verify TOTP",
"provider": "OKTA",
"type": "token:software:totp",
"status": 0,
"id": "osthgek5jmWTckcka0h7"
}, {
"name": "Unknown",
"provider": "CUSTOM",
"type": "claims_provider",
"status": 1,
"id": "clpn4wdtqtH6geILD0h7"
}, {
"name": "Google Authenticator",
"provider": "GOOGLE",
"type": "token:software:totp",
"status": 1,
"id": null
}]
const values = Object.values(
data.reduce((a, b) => {
if (!a[b.provider]) a[b.provider] = b
return a
}, {})
)
console.log(values)

Accessing data in an object and creating new object with filtered data

I am trying to search for specific nodes within an object and display a new object with the required data. There could be single or multiple fields in each composite type like displayed below.
This is the original object:
{
"section": "personal",
"fields": [
{
"type": "composite",
"name": "name",
"label": "Name",
"fields": [
{
"type": "text",
"name": "given",
"label": "First name",
"value": "Joe"
},
{
"type": "text",
"name": "family",
"label": "Last name",
"value": "Smith"
}
]
},
{
"type": "composite",
"name": "address",
"label": "Address",
"fields": [
{
"type": "text",
"name": "streetName",
"label": "Street Name",
"value": "1 High St"
},
{
"type": "text",
"name": "city",
"label": "City",
"value": "New York"
}
]
}
]
}
The resulting object should look like this:
{
name: {
given: "Joe",
family: "Smith",
},
address: {
streetName: "1 Hight St",
city: "New York"
}
}
EDIT*** Ideally, I'd like to figure out a way to use javascript methods (map/reduce/filter) and/or lodash to come up with an answer.
This is more an outline of what i've been looking at so far with built in methods.
var convertVals = function() {
var data = fields.fields;
var filter = data.filter(function(form) {
return form
})
.filter(function(form) {
return form.name && form.fields;
})
.map(function(form) {
return {form.name, [form.name.name]: form.name.value};
})
};
convertVals();
Thanks,
You can use Array.prototype.reduce() to iterate nested fields arrays. Set "name" property value of parent object as property name of object with value set to object set to "name" and "value" properties of objects within child "fields" array
var data = {
"section": "personal",
"fields": [
{
"type": "composite",
"name": "name",
"label": "Name",
"fields": [
{
"type": "text",
"name": "given",
"label": "First name",
"value": "Joe"
},
{
"type": "text",
"name": "family",
"label": "Last name",
"value": "Smith"
}
]
},
{
"type": "composite",
"name": "address",
"label": "Address",
"fields": [
{
"type": "text",
"name": "streetName",
"label": "Street Name",
"value": "1 High St"
},
{
"type": "text",
"name": "city",
"label": "City",
"value": "New York"
}
]
}
]
}
var res = data.fields.reduce((o, {name, fields}) =>
(o[name] = fields.reduce((curr, {name:key, value}) =>
(curr[key] = value, curr),{}), o), {});
console.log(res);
Well, here you go! Figured I might as well take a crack at it as no more questions were coming in.
var originalObject = {
"section": "personal",
"fields": [
{
"type": "composite",
"name": "name",
"label": "Name",
"fields": [
{
"type": "text",
"name": "given",
"label": "First name",
"value": "Joe"
},
{
"type": "text",
"name": "family",
"label": "Last name",
"value": "Smith"
}
]
},
{
"type": "composite",
"name": "address",
"label": "Address",
"fields": [
{
"type": "text",
"name": "streetName",
"label": "Street Name",
"value": "1 High St"
},
{
"type": "text",
"name": "city",
"label": "City",
"value": "New York"
}
]
}
]
};
function convertVals(obj){
var retObj = {};
for(var i=0;i<obj.fields.length;i++){
var tempObj={};
for(var j=0;j<obj.fields[i].fields.length;j++){
tempObj[obj.fields[i].fields[j].name] = obj.fields[i].fields[j].value;
}
retObj[obj.fields[i].name] = tempObj;
}
return retObj;
}
console.log(convertVals(originalObject));
/*
Should return:
{
name: {
given: "Joe",
family: "Smith",
},
address: {
streetName: "1 Hight St",
city: "New York"
}
}
*/
Here's a lodash solution that uses keyBy to assign the keys for each fields and mapValues to get the value for each field.
function getFields(data) {
return data.value || _(data.fields)
.keyBy('name')
.mapValues(getFields)
.value();
}
var data = {
"section": "personal",
"fields": [{
"type": "composite",
"name": "name",
"label": "Name",
"fields": [{
"type": "text",
"name": "given",
"label": "First name",
"value": "Joe"
},
{
"type": "text",
"name": "family",
"label": "Last name",
"value": "Smith"
}
]
},
{
"type": "composite",
"name": "address",
"label": "Address",
"fields": [{
"type": "text",
"name": "streetName",
"label": "Street Name",
"value": "1 High St"
},
{
"type": "text",
"name": "city",
"label": "City",
"value": "New York"
}
]
}
]
};
function getFields(data) {
return data.value || _(data.fields)
.keyBy('name')
.mapValues(getFields)
.value();
}
console.log(getFields(data));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
There is a hidden implication in the solution above, if the value contains falsey values then it would dismiss this value instead and assume that there's a fields value. To solve this, we can use has to check if a value key exists and then perform the same operations that we did above.
function getFields(data) {
return _.has(data, 'value')? data.value:
_(data.fields)
.keyBy('name')
.mapValues(getFields)
.value();
}
var data = {
"section": "personal",
"fields": [{
"type": "composite",
"name": "name",
"label": "Name",
"fields": [{
"type": "text",
"name": "given",
"label": "First name",
"value": "Joe"
},
{
"type": "text",
"name": "family",
"label": "Last name",
"value": "Smith"
}
]
},
{
"type": "composite",
"name": "address",
"label": "Address",
"fields": [{
"type": "text",
"name": "streetName",
"label": "Street Name",
"value": "1 High St"
},
{
"type": "text",
"name": "city",
"label": "City",
"value": "New York"
}
]
}
]
};
function getFields(data) {
return _.has(data, 'value')? data.value:
_(data.fields)
.keyBy('name')
.mapValues(getFields)
.value();
}
console.log(getFields(data));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Jquery Javascript object - compare and replace some of the values with another similar object

There is an Javascript object (formData) that I need to replace some of the values by comparing with another object (dataObject). The JSON for both objects is below. Now what I need is, snippet:
Main formData Object:
{
"name": "abNotes",
"label": "Ab Notes: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "Example Notes",
"active": true
}
I need to compare the "value" to the other dataObject by "name" property and replace if it's different.
dataObject to compare to:
{
"name": "abNotes",
"value": "Example Notes 123456"
}
So the replaced FormData object will be changed to:
{
"name": "abNotes",
"label": "Ab Notes: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "Example Notes 123456",
"active": true
}
Main object that needs to be replaced
JSON.stringify (formData);
form data::
{
"name": "Demo",
"fieldGroupList": [{
"name": "instructions",
"label": "Instructions",
"fieldList": [{
"name": "INSTRUCTION",
"instructionList": [{
"instructionText": "All enabled fields are required."
}],
"type": "INSTRUCTION"
}]
},
{
"name": "ab",
"label": "Ab",
"fieldList": [{
"name": "abDate",
"label": "Ab Date",
"type": "DATE",
"value": "1425186000000",
"active": true
},
{
"name": "abNotes",
"label": "Ab Notes: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "Example Notes",
"active": true
}]
},
{
"name": "Record",
"label": "Record",
"fieldList": [{
"name": "RecordNumber",
"label": "Record Number: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "1234567890",
"active": true
},
{
"name": "otherNumber",
"label": "Other: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "887766",
"active": true
},
{
"name": "eligibleAll",
"instructionList": [{
"instructionText": "Is eligible for ALL?"
}],
"type": "SINGLE_FROM_SET",
"value": "true",
"optionList": [{
"name": "Yes",
"value": "true"
},
{
"name": "No",
"value": "false"
}],
"active": true
},
{
"name": "exclusionReasonCode",
"instructionList": [{
"instructionText": "Select from the following list of sample:"
}],
"type": "SINGLE_FROM_SET",
"value": "DCS",
"optionList": [{
"name": "DCS",
"value": "Test"
}],
"active": true
}]
},
{
"name": "bDemo",
"label": "Demo",
"fieldList": [{
"name": "mId",
"label": "M ID:",
"type": "TEXT_BOX_SINGLE",
"active": false
},
{
"name": "firstName",
"label": "First Name:",
"type": "TEXT_BOX_SINGLE",
"value": "John",
"active": true
},
{
"name": "lastName",
"label": "Last Name",
"type": "TEXT_BOX_SINGLE",
"value": "Doe",
"active": true
},
{
"name": "genderCode",
"instructionList": [{
"instructionText": "Gender:"
}],
"type": "SINGLE_FROM_SET",
"optionList": [{
"name": "FEMALE",
"value": "FEMALE"
},
{
"name": "MALE",
"value": "MALE"
},
{
"name": "UNKNOWN",
"value": "UNKNOWN"
}],
"active": true
},
{
"name": "dateOfBirth",
"label": "Date of Birth:",
"type": "DATE",
"value": "-157748400000",
"active": true
}]
},
{
"name": "generalComments",
"label": "General Comments",
"fieldList": [{
"name": "comments",
"label": "Comments: (Optional)",
"type": "TEXT_BOX_MULTIPLE",
"value": "Comments Text Example",
"active": true
}]
}],
"Id": 1,
"periodId": 2015,
"orgId": 4,
"version": 1
}
The values that I need from this object:
var dataObject = $('#'+formName).serializeArray();
console.log("data:::"+JSON.stringify(dataObject));
dataObject:::
[{
"name": "abDate",
"value": "Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)"
},
{
"name": "abNotes",
"value": "Example Notes 123456"
},
{
"name": "Number",
"value": "1234567890"
},
{
"name": "otherNumber",
"value": "887766"
},
{
"name": "Yes",
"value": "true"
},
{
"name": "No",
"value": "false"
},
{
"name": "DCS",
"value": "Test"
},
{
"name": "firstName",
"value": "John"
},
{
"name": "lastName",
"value": "Doe"
},
{
"name": "FEMALE",
"value": "FEMALE"
},
{
"name": "MALE",
"value": "MALE"
},
{
"name": "UNKNOWN",
"value": "UNKNOWN"
},
{
"name": "dateOfBirth",
"value": "Fri Jan 01 1965 00:00:00 GMT-0500 (Eastern Standard Time)"
},
{
"name": "comments",
"value": "Comments Text Example"
}]
EDIT:
What I have tried so far:
$.extend(formData ,dataObject);
deepCopy:
function deepCopy(src, dest) {
var name,
value,
isArray,
toString = Object.prototype.toString;
// If no `dest`, create one
if (!dest) {
isArray = toString.call(src) === "[object Array]";
if (isArray) {
dest = [];
dest.length = src.length;
}
else { // You could have lots of checks here for other types of objects
dest = {};
}
}
// Loop through the props
for (name in src) {
// If you don't want to copy inherited properties, add a `hasOwnProperty` check here
// In our case, we only do that for arrays, but it depends on your needs
if (!isArray || src.hasOwnProperty(name)) {
value = src[name];
if (typeof value === "object") {
// Recurse
value = deepCopy(value);
}
dest[name] = value;
}
}
return dest;
}
First, convert dataObject from an array of objects to an object that maps names to values. Then go through the main form data, replacing values from the corresponding elements of doHash.
var formData = {
"name": "Demo",
"fieldGroupList": [{
"name": "instructions",
"label": "Instructions",
"fieldList": [{
"name": "INSTRUCTION",
"instructionList": [{
"instructionText": "All enabled fields are required."
}],
"type": "INSTRUCTION"
}]
}, {
"name": "ab",
"label": "Ab",
"fieldList": [{
"name": "abDate",
"label": "Ab Date",
"type": "DATE",
"value": "1425186000000",
"active": true
}, {
"name": "abNotes",
"label": "Ab Notes: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "Example Notes",
"active": true
}]
}, {
"name": "Record",
"label": "Record",
"fieldList": [{
"name": "RecordNumber",
"label": "Record Number: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "1234567890",
"active": true
}, {
"name": "otherNumber",
"label": "Other: (Optional)",
"type": "TEXT_BOX_SINGLE",
"value": "887766",
"active": true
}, {
"name": "eligibleAll",
"instructionList": [{
"instructionText": "Is eligible for ALL?"
}],
"type": "SINGLE_FROM_SET",
"value": "true",
"optionList": [{
"name": "Yes",
"value": "true"
}, {
"name": "No",
"value": "false"
}],
"active": true
}, {
"name": "exclusionReasonCode",
"instructionList": [{
"instructionText": "Select from the following list of sample:"
}],
"type": "SINGLE_FROM_SET",
"value": "DCS",
"optionList": [{
"name": "DCS",
"value": "Test"
}],
"active": true
}]
}, {
"name": "bDemo",
"label": "Demo",
"fieldList": [{
"name": "mId",
"label": "M ID:",
"type": "TEXT_BOX_SINGLE",
"active": false
}, {
"name": "firstName",
"label": "First Name:",
"type": "TEXT_BOX_SINGLE",
"value": "John",
"active": true
}, {
"name": "lastName",
"label": "Last Name",
"type": "TEXT_BOX_SINGLE",
"value": "Doe",
"active": true
}, {
"name": "genderCode",
"instructionList": [{
"instructionText": "Gender:"
}],
"type": "SINGLE_FROM_SET",
"optionList": [{
"name": "FEMALE",
"value": "FEMALE"
}, {
"name": "MALE",
"value": "MALE"
}, {
"name": "UNKNOWN",
"value": "UNKNOWN"
}],
"active": true
}, {
"name": "dateOfBirth",
"label": "Date of Birth:",
"type": "DATE",
"value": "-157748400000",
"active": true
}]
}, {
"name": "generalComments",
"label": "General Comments",
"fieldList": [{
"name": "comments",
"label": "Comments: (Optional)",
"type": "TEXT_BOX_MULTIPLE",
"value": "Comments Text Example",
"active": true
}]
}],
"Id": 1,
"periodId": 2015,
"orgId": 4,
"version": 1
};
var dataObject = [{
"name": "abDate",
"value": "Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)"
}, {
"name": "abNotes",
"value": "Example Notes 123456"
}, {
"name": "Number",
"value": "1234567890"
}, {
"name": "otherNumber",
"value": "887766"
}, {
"name": "Yes",
"value": "true"
}, {
"name": "No",
"value": "false"
}, {
"name": "DCS",
"value": "Test"
}, {
"name": "firstName",
"value": "John"
}, {
"name": "lastName",
"value": "Doe"
}, {
"name": "FEMALE",
"value": "FEMALE"
}, {
"name": "MALE",
"value": "MALE"
}, {
"name": "UNKNOWN",
"value": "UNKNOWN"
}, {
"name": "dateOfBirth",
"value": "Fri Jan 01 1965 00:00:00 GMT-0500 (Eastern Standard Time)"
}, {
"name": "comments",
"value": "Comments Text Example"
}];
var doHash = {};
$.each(dataObject, function() {
doHash[this.name] = this.value;
});
$.each(formData.fieldGroupList, function() {
$.each(this.fieldList, function() {
if (this.name in doHash) {
this.value = doHash[this.name];
}
});
});
console.log(JSON.stringify(formData));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources