creating an object from JSON data - javascript

I have the following data in a .json file:
{
"countries": {
"sweden": {
"currency": "Swedish krona",
"majorLanguage": "Swedish",
"landArea": {
"value": 410330,
"uom": "sq km"
}
},
"japan": {
"currency": "yen",
"majorLanguage": "Japanese",
"landArea": {
"value": 364500,
"uom": "sq km"
}
},
"unitedStatesOfAmerica": {
"currency": "US dollar",
"majorLanguage": "English",
"landArea": {
"value": 3796742,
"uom": "sq mi"
}
}
}
}
and need to come up with a way to create this object from it:
Object {
"currency": Object {
"japan": "yen",
"sweden": "Swedish krona",
"unitedStatesOfAmerica": "US dollar"
},
"majorLanguage": Object {
"japan": "Japanese",
"sweden": "Swedish",
"unitedStatesOfAmerica": "English"
},
"landArea": Object {
"japan": Object {
"value": 364500,
"uom": "sq km"
},
"sweden": Object {
"value": 410330,
"uom": "sq km"
},
"unitedStatesOfAmerica": Object {
"value": 3796742,
"uom": "sq mi"
}
}
}
The app that will be consuming this data is written in Vue so using JavaScript to accomplish this would make sense, although my preference is to not use any third party libraries. Specifically, I'm interested in a programmatic approach that doesn't require hard coding of to manually create objects for currency, majorLanguage, landArea. I don't really know how to start tackling this so don't have any sample attempts to post here.

Nothing fancy here:
const result = {};
for (const name in countries) {
const country = countries[name];
for (const key in country) {
if (!result[key]) result[key] = {};
result[key][name] = country[key];
}
}

You can use Array#reduce method and do something like the following.
const data = {"countries":{"sweden":{"currency":"Swedish krona","majorLanguage":"Swedish","landArea":{"value":410330,"uom":"sq km"}},"japan":{"currency":"yen","majorLanguage":"Japanese","landArea":{"value":364500,"uom":"sq km"}},"unitedStatesOfAmerica":{"currency":"US dollar","majorLanguage":"English","landArea":{"value":3796742,"uom":"sq mi"}}}};
// iterate over countries object key value pair
const res = Object.entries(data.countries).reduce((obj, [country, valObj]) => {
// iterate over the country value key-val pair
Object.entries(valObj).forEach(([key, val]) => {
// define key if not defined
obj[key] = obj[key] || {};
// define the value within object where key is country
obj[key][country] = val;
})
return obj;
}, {})
console.log(res);

Related

Filter an nested Object with filter and map with JavaScript

I know that this is close to a duplicate but I can't get the code to work. I have an object that I need to filter and I'm currently trying to emulate the accepted as an answer the code at Javascript filtering nested arrays
My data object is:
[{
"project_num": "5R01DA012513-23",
"principal_investigators": [{
"profile_id": 2076451,
"full_name": "PK",
"title": ""
}]
},
{
"project_num": "5R01DK118529-03",
"principal_investigators": [{
"profile_id": 8590844,
"full_name": "HW",
"title": "PROFESSOR, SCIENTIFIC DIRECTOR"
}]
},
{
"project_num": "3R01AA025365-05S1",
"principal_investigators": [{
"profile_id": 8730036,
"full_name": "JJ",
"title": "ASSOCIATE PROFESSOR OF PSYCHIATRY"
}]
},
{
"project_num": "1R01HL163963-01",
"principal_investigators": [{
"profile_id": 2084037,
"full_name": "KH",
"title": "ASSOCIATE PROFESSOR"
},
{
"profile_id": 11309656,
"full_name": "AM",
"title": "RESEARCH ASSISTANT PROFESSOR"
}
]
},
{
"project_num": "5R25HL092611-15",
"principal_investigators": [{
"profile_id": 1886512,
"full_name": "CW",
"title": "P"
}]
}
]
and my JavaScript code is:
let payLoad = 1886512
const result = this.reporterData.map(t => {
const principal_investigators = t.principal_investigators.filter(d =>
d.profile_id === payLoad);
return { ...t,
principal_investigators
};
})
I need to pass in a profile_id as a payload and return the objects that will fill a data table.
The data can be 1000's of items and the principla_investigators can be multiple entries. When I use the code that I have it return all of the objects. Can someone point out my error? Thanks
You can try doing like this:
const result = this.reporterData.filter((t) => {
const principal_investigators = t.principal_investigators.filter((d) => d.profile_id === payLoad)
return (principal_investigators.length > 0)
})
I understand that you want an array with all the investigators matching that ID, right?
Try this:
const result = this.reporterData.reduce((previous, current) => {
if (current.principal_investigators) {
current.principal_investigators.forEach(pi => {
if (pi.profile_id === payLoad) {
previous.push(current)
}
});
}
return previous
}, [])
You can also do for loops with the same result:
const result = [];
for (project of this.reporterData) {
if (project.principal_investigators) {
for (pi of project.principal_investigators) {
if (pi.profile_id == payLoad) {
result.push(pi);
}
}
}
}

Javascript -sort array based on another javascript object properties

I have one javascript array and one object . Need help to sort javascript object keys based on the order number in another array
In subgroup array , I have name , order number. Need to sort Offerings keys based on that order number
const subgroup = [
{
"code": "6748",
"name": "test123",
"orderNumber": "0"
},
{
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}
]
const offerings = {
"customdata" : [
{
"code": "Audi",
"color": "black"
}
],
"test123" : [
{
"brand": "Audi",
"color": "black"
}
]
}
I believe this should work for you. I've added some comments in the code that should hopefully do an okay job of explaining what is happening.
var subgroup = [{
"code": "6748",
"name": "test123",
"orderNumber": "0"
}, {
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}];
var offerings = {
"customdata": [{
"code": "Audi",
"color": "black"
}],
"test123": [{
"brand": "Audi",
"color": "black"
}]
}
function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') {
// Get copy of refArray
let reference = refArray.slice();
// Sort sortObject [ into an array at this point ]
let sorted = [];
for (let key in sortObject) {
// Searches the refArray for the linkKey, and returns the intended index
let index = reference.find((item) => item[linkKey] === key)[orderKey];
// Places the sortObject's value in the correct index of the 'sorted' Array
sorted[parseInt(index)] = [key, sortObject[key]];
};
// Return an object, created from previous 'sorted' Array
return sorted.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name');
console.log(offerings);

Can't Use MAP data structure in Node.js

I have getting some issue in map program in node.js. I am trying to use MAP into node.js program and I am not getting value.I have write some code to use map however I think it not working as its not go into the loop to fetch the key-value.
Please find below program
async CreateProduceMVPRateAsset(data, callback) {
var ProducePRICE = {};
var MVPPRICE =[];
var MVPPRICE_BS ={};
var MVPPRICE_LB ={};
//var ASKINGPRICE= {}// put all the things which need to go to blockchain
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Data', data);
console.log('Username', data.username);
var PRODUCENAME = data.PRODUCE
console.log('PRODUCENAME', PRODUCENAME);
var COUNTRY = data.COUNTRY;
console.log('COUNTRY', COUNTRY);
var STATE = data.STATE;
console.log('STATE', STATE);
var MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', MVPRATES);
const MVPRATE = new Map(MVPRATES);
// program could not go inside the for loop
for (const [k, v] of MVPRATE.entries()) {
console.log("Inside map", k, v)
MVPPRICE = v.RATE // should go in MVPPRICE
var Value = MVPPRICE[0].value // want to get first element value from MVPPRICE array
console.log('Value', Value);
var value_lb = Value/40;
console.log('value_lb', value_lb);
value_lb = Number((value_lb).toFixed(4));
console.log('If the value of BS provided controller come here');
MVPPRICE_LB.Value = value_lb
MVPPRICE_LB.QuantityUnit = 'LB'
MVPPRICE_LB.uidisplay = false
MVPPRICE_LB.CurrencyUnit = 'USD'
MVPPRICE.push(MVPPRICE_LB);
ProducePRICE.MVPPRICE = MVPPRICE
console.log('MVPPRICE',MVPPRICE);
console.log('ProducePRICE',ProducePRICE);
// mvpprice.totalPrice = totalPrice;
console.log('for pricing',totalPrice);
// ProducePRICE.VARIETY = VARIETY;
ProducePRICE.PRODUCENAME = PRODUCENAME;
ProducePRICE.STATE = STATE;
ProducePRICE.COUNTRY = COUNTRY;
}
JSON structure which I am sending using postman
{
"username": "admin2",
"PRODUCE": "Apple",
"STATE": "MI",
"COUNTRY": "US",
"MVPRATES": {
"fuji": {
"VARIETY": "fuji",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
},
"gala": {
"VARIETY": "gala",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
}
}
}
Output which I am getting:
Seems like you may want to do the following, this creates a Map with two entries, fuji and gala
const MVPRATES = {
"fuji": {
"VARIETY": "fuji",
"RATE": [{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}]
},
"gala": {
"VARIETY": "gala",
"RATE": [{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}]
}
}
const MVPRATE = new Map(Object.entries(MVPRATES));
for (const [k, v] of MVPRATE.entries()) {
console.log("Inside map", k, v)
}
Though, the need for Map is still unclear, as you can achieve the above with
const MVPRATES = {
"fuji": {
"VARIETY": "fuji",
"RATE": [{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}]
},
"gala": {
"VARIETY": "gala",
"RATE": [{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}]
}
}
for (const [k, v] of Object.entries(MVPRATES)) {
console.log("Inside map", k, v)
}

How does new Map() works in javascript when the json has keys with same name

I have a JSON structure and code like below :
const villages =
{
"lossesOccured":
[
{
"type": "destroyed",
"affectedOn": "humans",
"quantity": 120,
"reliefFund": 100000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
]
}
const lossesArray = villages.lossesOccured
let myMap = new Map()
lossesArray.forEach(loss => {
if(loss.affectedOn === "humans"){
myMap.set(loss.affectedOn,loss)
}
})
console.log(myMap)
Initialised a new Map and assigned key,values to it.
Key is "affectedOn".
Since there are same key names(affectedOn) in many elements, map eliminates all duplicates and prints only one. Is there a way to print all the key values even-though it has same name.
Thanks in advance.
Output:
A Map has key-value pairs, similar to an object, and will have a value for every distinct key. (If you want to use keys k1 and k2, and k1 === k2, and you call myMap.set(k1 and then later myMap.set(k2, then the initial value assigned by k1 will be overwritten.)
If you want to turn everything in your input array into a Map, one way to make sure the keys are unique would be to make the keys objects (which won't be === to each other):
myMap.set({ key: loss.affectedOn }, loss);
const villages = {
"lossesOccured": [{
"type": "destroyed",
"affectedOn": "humans",
"quantity": 120,
"reliefFund": 100000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
]
}
const lossesArray = villages.lossesOccured
const myMap = new Map();
lossesArray.forEach(loss => {
if (loss.affectedOn === "humans") {
myMap.set({ key: loss.affectedOn }, loss);
}
});
console.log(myMap);

Object manipulation

I am using either PHP or Javascript to manipulate an json object from API sample:
{
"data": [
{
"label": "employeeCount",
"stats": [
{
"year": "2015",
"value": "10"
},
{
"year": "2017",
"value": "30"
},
{
"year": "2016",
"value": "50"
}
]
},
{
"label": "managerCount",
"stats": [
{
"year": "2015",
"value": "2"
},
{
"year": "2017",
"value": "4"
},
{
"year": "2016",
"value": "6"
}
]
}
]
}
I need to categorize it by the year as object like such:
"record": {
"2015" : {
"employeeCount": "10",
"managerCount": "2"
},
"2016" : {
"employeeCount": "30",
"managerCount": "4"
},
"2017"{
"employeeCount": "50",
"managerCount": "6"
}
}
The number of year and the number of label will be different from the API call so I am thinking about using a for loop to make it happen. But so far no success. What approach would you use for this kind of manipulation?
Use Array.forEach
LOGIC - Idea is to iterate over data array in object and then for each entry in data array, iterate over its corresponding stats array to populate the object based on year. While iterating over the stat array, check for existing entry in resultant object. If does not exist, create an entry for it. Update the entry by adding the label as key and value from its corresponding object in stat array.
let obj = {"data":[{"label":"employeeCount","stats":[{"year":"2015","value":"10"},{"year":"2017","value":"30"},{"year":"2016","value":"50"}]},{"label":"managerCount","stats":[{"year":"2015","value":"2"},{"year":"2017","value":"4"},{"year":"2016","value":"6"}]}]};
// Create the response object
let r = {"record":{}};
// Iterate over data array
obj.data.forEach(o => {
// Iterate over stats for each object in data array
o.stats.forEach(s => {
// Create entry for year in result object if it does not exist
r.record[s.year] = r.record[s.year] || {};
// Add the label of data array object with corresponding stat value in resultant object
r.record[s.year][o.label] = s.value;
});
});
console.log(r);
let data = json.data
let map={}
for(let i=0;i<data.length;i++){
let stats = data[i].stats
for(let j=0;j<stats.length;j++){
let it = stats[j]
if(!map[it.year]){
map[it.year]={}
}
map[it.year][data[i].label]=it.value
}
}
console.log({record:map})

Categories

Resources