Javascript convert object key names based on mapping - javascript

I have a javascript object that is coming from Source1 and I am unable to change its native structure or naming convention. I am using this data to feed into a 3rd party plugin to generate some chart data. This plugin however is using the key names as the identifiers on the chart and they are not descriptive or clear enough.
I am trying to run the object through a conversion function where it will change all of the key names to their defined equivalent.
Here is an example of what I am trying to do:
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
function convertNames(obj){
// Converted names
var map = [{
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}];
// Loop through the object and convert all key names to their equivalent
for(var prop in obj){
// Convert Here
}
return obj;
}
Desired Output:
[{
SubmissionIdentifier: "28935",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "No",
},
{
SubmissionIdentifier: "28936",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "Yes",
}]
https://jsfiddle.net/hbg4sfqh/7/

I'd combine the .map array method and a function to convert your key names to get the result you want. To convert the key names, you'll want to use bracket notation, so something like: newObj[keyMap[oldKey]] = oldObj[oldKey] should work.
Here's a simple implementation for your example:
const obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
}, {
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}];
const nameMap = {
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}
function renameKeys(obj, map) {
const newObj = {};
for (let key in obj) {
newObj[map[key]] = obj[key];
}
return newObj;
}
console.log(obj.map(item => renameKeys(item, nameMap)));
I'd also note that if you happen to be using the lodash library, you can also use it's _.mapKeys method to do this.

I'm gonna use .map() function to change the key names. The input data will remain unchanged. Hope this helps.
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
var output = obj.map(element => ({
SubmissionIdentifier: element.SubmissionID,
CreationDate: element.MetaCreatedDate,
ProgramName: element.Program,
Viewed: element.ViewedByInvestigator
}));

Related

Convert csv output toobject with nested arrays and objects using javascript

I have object after CSV conversion in this shape:
const data = {
"assets/0/description": "propertyImage",
"assets/0/filename": "a31989e07277954d93bca65e2d02dcb9.jpeg?p=cc_vo_small",
"assets/0/mimetype": "jpeg?p=cc_vo_small",
"assets/0/ordinal": "0",
"assets/0/url": "/usados/2022/09/04/0/a31989e07277954d93bca65e2d02dcb9.jpeg?p=cc_vo_small",
"assets/1/description": "propertyImage",
"assets/1/filename": "3bc3a9a4982508941ea178cca2ad31f1.jpeg?p=cc_vo_small",
"assets/1/mimetype": "jpeg?p=cc_vo_small",
"assets/1/ordinal": "1",
"assets/1/url": "",
combustion: "diesel",
createdAt: "2022-09-14T13:42:55.807Z",
engine: "235 CV",
firstDateRegistration: "2021",
gearbox: "automática secuencial",
"location/city": "Vitoria-Gasteiz",
"location/country": "España",
"location/distributor": "",
"location/houseNumber": "",
"location/postalCode": "",
"location/province": "Alava",
"location/street": "C/ Portal de Betoño, 13-15",
make: "volvo",
"metadata/0/key": "Año",
"metadata/0/value": "2021",
mileage: "29000",
model: "v90 cross country b5 pro awd aut.",
"optionals/0": "",
originalColorString: "gris",
"price/currency": "EUR",
"price/financialPrice": "53700",
"price/price": "56999",
saleDate: "Wed Sep 14 2022",
seller_type: "professional",
traction: "",
version: "V90 Cross Country B5 Pro Awd Aut."
};
Im trying to convert nested items that csv made flat into the correct format:
assets/0/description -> {
assets: [
{
description: "propertyImage",
filename: "...",
...
}
]
}
probably number between is an array and just / is an object. I tried to build reduce function and create it recursively but it looks more complicated than this. Any chance that there is a library for it? Or has someone already met this problem in the past?

getTime() method behaves differently in js

I have an array of object like :
[
{
"order_id": 1,
"customer": "Karita Klimochkin",
"country": "Sweden",
"address": "8978 Westridge Park",
"product_title": "Yellow-bellied marmot",
"product_description": "Bread - Flat Bread",
"date": "21/08/2020",
"status": "Delivered"
},
{
"order_id": 2,
"customer": "Ferne Roman",
"country": "China",
"address": "1370 Ridge Oak Pass",
"product_title": "Two-toed sloth",
"product_description": "Asparagus - White, Fresh",
"date": "24/07/2020",
"status": "Completed"
}
]
I want to sort objects by date. so when I use getTime() method it gives me different result.
orders.map(order => new Date(order.date).getTime())
results are :
1628100000000
NaN
What is the problem here?
You need to convert the date to mm/dd/yyyy format from dd/mm/yyyy so that JS can understand it properly
orders.map(order => {
const parts= order.date.split("/")
return new Date(`${parts[1]}/${parts[0]}/${parts[2]}`).getTime()
})
You cannot count on the default date parser to parse your DD/MM/YYYY format correctly. Parsing date strings through the constructor in this way is highly discouraged because it is implementation-dependent. Different browsers/runtimes will parse dates differently.
Instead, manually parse the date yourself and then construct the date object:
orders.map(order => {
const [d, m, y] = order.date.split('/');
return +new Date(+y, m-1, +d);
})
Friendly reminder: do you have a sorting functionality yet? .map is just an iteration through your array.
More about map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Add a sort function based on your date(properly parsed) property and return a new array would help.
The dates are in the wrong format:
// from: "21/08/2020"
let format = obj.date.split('/').reverse().join('-')
// to: "2020-08-21"
In order to be sortable, dates must be in ms since Jan 1, 1970. Assign the new value to a new key:
obj.pDate = Date.parse(format);
Sort by the new key/value:
let results = orders.sort((a, b) => a.pDate = b.pDate)
Then remove all of the new key/values:
results.map(order => delete order.pDate)
const data = [{
"order_id": 1,
"customer": "Karita Klimochkin",
"country": "Sweden",
"address": "8978 Westridge Park",
"product_title": "Yellow-bellied marmot",
"product_description": "Bread - Flat Bread",
"date": "21/08/2020",
"status": "Delivered"
},
{
"order_id": 2,
"customer": "Ferne Roman",
"country": "China",
"address": "1370 Ridge Oak Pass",
"product_title": "Two-toed sloth",
"product_description": "Asparagus - White, Fresh",
"date": "24/07/2020",
"status": "Completed"
}, {
"order_id": 3,
"customer": "zer00ne",
"country": "US",
"address": "123 Main St",
"product_title": "Jackalope",
"product_description": "Chili Cheese Fries",
"date": "12/05/2020",
"status": "Delivered"
},
];
const sortOrders = orders => {
let result = orders.sort((a, b) => {
a.pDate = Date.parse(a.date.split('/').reverse().join('-'));
b.pDate = Date.parse(b.date.split('/').reverse().join('-'));
return a.pDate - b.pDate;
})
result.map(order => delete order.pDate);
return result;
};
console.log(sortOrders(data));

React Native how to create a VictoryPie from nested data

In my React Native application, I am accessing data from my store in the following form:
Array [
Checkout {
"date": 2020-12-27T13:24:08.734Z,
"id": "Sun Dec 27 2020 08:24:08 GMT-0500 (EST)",
"items": Array [
Object {
"productBrand": "Microsoft",
"productCategory": "Gaming",
"productId": "p1",
"productTitle": "Xbox",
"quantity": 2,
"x": 1.815,
},
Object {
"productBrand": "Apple",
"productCategory": "Computers",
"productId": "p2",
"productTitle": "MacBook Pro",
"quantity": 1,
"x": 1.905,
},
],
"total": 3.720,
},
Checkout {
"date": 2020-12-27T13:24:47.790Z,
"id": "Sun Dec 27 2020 08:24:47 GMT-0500 (EST)",
"items": Array [
Object {
"productBrand": "Apple",
"productCategory": "Computers",
"productId": "p2",
"productTitle": "MacBook Pro",
"quantity": 1,
"x": 1.905,
},
],
"total": 1.905,
},
]
I am trying to use VictoryPie to create a pie chart that shows productBrand weighted by the sum of x over all the objects. In this example, I would need a pie chart showing Microsoft and Apple, weighted by 1.815 and 2*1.905 = 3.81, respectively. Is there any way to do this without writing a separate function to calculate these sums? I would like the pie chart to update automatically every time new data is added to the store.
I tried this, where history is a variable containing the above array but no pie chart is produced.
<VictoryPie data={history} x={(data) => data.items.productBrand} y={(data) => data.items.x} />
See my working sample: https://codesandbox.io/s/react-victory-pie-chart-forked-kpe39?file=/src/index.js
Like this:
x="productBrand"
y={(data) => data.x * data.quantity}
For anyone trying to do something similar, I ended up extracting the data I needed by using a nested for loop within the useSelector hook:
const allBrands = useSelector(state => {
let allData = {};
for (const key1 in state.history.history) {
for (const key2 in state.history.history[key1].items) {
if (allData.hasOwnProperty(state.history.history[key1].items[key2].productBrand)) {
allData[state.history.history[key1].items[key2].productBrand] += state.history.history[key1].items[key2].x;
} else {
allData[state.history.history[key1].items[key2].productBrand] = state.history.history[key1].items[key2].x;
}
}
};
let dataArray = [];
for (const prop in allData) {
dataArray.push({ brand: prop, total: allData[prop] })
}
return dataArray
});
Passing allBrands to the VictoryPie data prop produced the correct pie chart.

how to get particular Keys Values from the exiting JSON Object in javacsript? [duplicate]

This question already has answers here:
How to get a subset of a javascript object's properties
(36 answers)
Closed 3 years ago.
I have one JSON Object and I want to create subset of JSON with particular keys values.
JSON Object
{
"Checksum": "OK",
"ID": "012B4567",
"DOB: "12-12-1991"
"Data": "Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>",
"issue: "11-April-2015",
"DocID": "PASSPORT",
"Number: "123456789",
"Document": "PASSPORT",
"Photo": "Qk06AAAAAAAAA",
"ExpiredFlag": false,
"ExpiryDate": "01 Apr 12",
"Forename": "IMA Phoney",
"Image2": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"ImageSource1": 0,
"Image3": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"Image1": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I want subset from above like below:
{
"ID": "012B4567",
"Number: "123456789",
"Document": "PASSPORT",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I have tried below code. It is working fine, But I am not able to understand. I need simplest way:
var data={
"CDRValidation": "CDR Validation test passed",
"AirBaudRate": "424",
"ChipID": "012B4567",
"BACStatus": "TS_SUCCESS",
"SACStatus": "TS_NOT_PERFORMED",
"Data": "Test Line 1 >>>>>\nTest Line 2 >>>>>\nTest Line 3 >>>>>",
"DocType": "PASSPORT",
"DocNumber": "123456789",
"DocID": "PASSPORT",
"Surname": "Person",
"Forename": "IMA Phoney",
"SecondName": "J",
"Nationality" : "Imaging Automation Demo State",
"Sex": "Male",
"DOB": "12 May 70",
"ExpiryDate": "01 Apr 12",
"IssueState": "Passport Agency Billerica",
"ExpiredFlag": false,
"ImageSource": 0,
"OptionalData1": "123456789123456",
"OptionalData2": "",
"DateOfIssue":"11 April 02",
"PlaceOfBirth":"Illinois, U.S.A"
}
console.log("----------------->",data);
var Fields = ({
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data, {
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
})
console.log("--------subset--------->",Fields);
There are multiple ways you can handle this case. Object destructuring as you have done in your example is one simple way. You can also use an array to store the required keys and write code as below
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
const obj = {};
for (let i = 0, length = keys.length; i < length; i += 1) {
obj[keys[i]] = parentObj[keys[i]];
}
return obj;
}
Or you can also use the above code with some functional programming
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
return keys.reduce((acc, key) => ({
...acc,
[key]: parentObj[key];
}), {});
}
A simple to achieve what you are asking using ES5 is to create a list of all the properties you want to keep, and using Array#reduce add each property to a new object.
// Saves vertical space for example
var original = JSON.parse(`{"Checksum":"OK","ID":"012B4567","DOB":"12-12-1991","Data":"Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>","issue":"11-April-2015","DocID":"PASSPORT","Number":"123456789","Document":"PASSPORT","Photo":"Qk06AAAAAAAAA","ExpiredFlag":false,"ExpiryDate":"01 Apr 12","Forename":"IMA Phoney","Image2":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","ImageSource1":0,"Image3":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","Image1":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","IssueState":"USA","Nationality":"USA","PlaceOfBirth":"U.S.A","SecondName":"J","Sex":"Male","Surname":"XYZ"}`);
var propertiesToUse = ["ID", "Number", "Document", "IssueState", "Nationality", "PlaceOfBirth", "SecondName", "Sex", "Surname"];
var result = propertiesToUse.reduce(function(result, key) {
return result[key] = original[key], result;
}, {});
console.log(result);
What you have done is a simple way, but if you are confused with it, you can divide it into two lines and explain it.
This line actually destrucutes your object and assign the value for the mentioned keys in the object to the corresponding variables.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data
Now, each of this variable has data individually, but we want it in an object. Therefore, we use the second part, i.e. creating an object with the following variable acting as keys.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
}
When combined you get the desired result in a single statement.

Javascript collection find values with Lodash

I have an array shown as below. I want to know which values inside departure and arrival fields.
Array :
var data = {
"origin": "Antalya",
"destination": "IST",
"flights": [{
"provider": "thy",
"time": "2017-07-07 10:30",
"legs": [{
"departure": "AYT",
"arrival": "IST"
}]
},{
"provider": "thy",
"time": "2017-07-07 14:30",
"legs": [{
"departure": "AYT",
"arrival": "ESB"
},{
"departure": "ESB",
"arrival": "IST"
}]
},{
"provider": "pegasus",
"time": "2017-07-07 06:30",
"legs": [{
"departure": "AYT",
"arrival": "ADB"
},{
"departure": "ADB",
"arrival": "IST"
}]
}]
};
I want to new array like this :
["AYT","IST","ESB","ADB"]
How can i handle it using lodash?
Here's a solution using lodash:
let result = _(data.flights)
.flatMap('legs')
.flatMap(_.values)
.uniq()
.value();
First we get a flattened array of legs, transform that into a flattened array of the values of the properties of each leg, before finally getting the unique values.
Well loop through your data and create a string array, and then use the uniq function, like:
var data = {"origin":"Antalya","destination":"IST","flights":[{"provider":"thy","time":"2017-07-07 10:30","legs":[{"departure":"AYT","arrival":"IST"}]},{"provider":"thy","time":"2017-07-07 14:30","legs":[{"departure":"AYT","arrival":"ESB"},{"departure":"ESB","arrival":"IST"}]},{"provider":"pegasus","time":"2017-07-07 06:30","legs":[{"departure":"AYT","arrival":"ADB"},{"departure":"ADB","arrival":"IST"}]}]};
var legs = [];
_.each(data.flights, flight => {
_.each(flight.legs, leg => {
legs.push(leg.departure);
legs.push(leg.arrival);
});
});
console.log(_.uniq(legs));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Categories

Resources