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)
}
Related
I am using Angular 13 and I have an array of objects like this:
[{
"name": "Operating System",
"checkedCount": 0,
"children": [{
"name": "Linux",
"value": "Redhat",
"checked": true
},
{
"name": "Windows",
"value": "Windows 10"
}
]
},
{
"name": "Software",
"checkedCount": 0,
"children": [{
"name": "Photoshop",
"value": "PS",
"checked": true
},
{
"name": "Dreamweaver",
"value": "DW"
},
{
"name": "Fireworks",
"value": "FW",
"checked": true
}
]
}
]
I would like to loop through the array, check if each object has a children array and it in turn has a checked property which is set to true, then I should update the checkedCount in the parent object. So, result should be like this:
[{
"name": "Operating System",
"checkedCount": 1,
"children": [{
"name": "Linux",
"value": "Redhat",
"checked": true
},
{
"name": "Windows",
"value": "Windows 10"
}
]
},
{
"name": "Software",
"checkedCount": 2,
"children": [{
"name": "Photoshop",
"value": "PS",
"checked": true
},
{
"name": "Dreamweaver",
"value": "DW"
},
{
"name": "Fireworks",
"value": "FW",
"checked": true
}
]
}
]
I tried to do it this way in angular, but this is in-efficient and results in an error saying this.allFilters[i].children[j] may be undefined. So, looking for an efficient manner to do this.
for(let j=0;i<this.allFilters[i].children.length; j++) {
if (Object.keys(this.allFilters[i].children[j]).length > 0) {
if (Object.prototype.hasOwnProperty.call(this.allFilters[i].children[j], 'checked')) {
if(this.allFilters[i].children[j].checked) {
this.allFilters[i].checkedCount++;
}
}
}
}
Use a nested for loop to check all the children. If checked is truthy, increment the count of the parent. You don't need to check if parent.children has any elements since if there are no elements the loop won't run anyways.
// minified data
const data = [{"name":"Operating System","checkedCount":0,"children":[{"name":"Linux","value":"Redhat","checked":!0},{"name":"Windows","value":"Windows 10"}]},{"name":"Software","checkedCount":0,"children":[{"name":"Photoshop","value":"PS","checked":!0},{"name":"Dreamweaver","value":"DW"},{"name":"Fireworks","value":"FW","checked":!0}]}];
for (const parent of data) {
for (const child of parent.children) {
if (child.checked) parent.checkedCount++;
}
}
console.log(data);
No need to complicate it like that, you just need to check checked property in children.
data.forEach((v) => {
v.children.forEach((child) => {
if (child.checked) {
v.checkedCount++;
}
});
});
Using filter + length on children array should do the job:
const data = [{"name":"Operating System","checkedCount":null,"children":[{"name":"Linux","value":"Redhat","checked":true},{"name":"Windows","value":"Windows 10"}]},{"name":"Software","checkedCount":null,"children":[{"name":"Photoshop","value":"PS","checked":true},{"name":"Dreamweaver","value":"DW"},{"name":"Fireworks","value":"FW","checked":true}]}];
data.forEach(itm => {
itm.checkedCount = itm.children?.filter(e => e.checked === true).length ?? 0;
});
console.log(input);
I would suggest going functional.
Using map
const children = arr.map(obj => obj.children);
const result = children.map((child, idx) => {
const checkedCount = child.filter(obj => obj.checked)?.length;
return {
...arr[idx],
checkedCount
};
});
console.log(result)
or using forEach
const result = [];
const children = arr.map(obj => obj.children);
children.forEach((child, idx) => {
const checkedCount = child.filter(obj => obj.checked)?.length;
result[idx] = {
...arr[idx],
checkedCount
};
});
console.log(result)
I have two array of objects, Based on one array I need to replace the key of another array. Tried to use Object.Keys() but could not achieve it. Kindly suggest
// **Input :**
let sim = {
"header": [{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
}
// **Reference Array:**
let columns = [{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
]
/// **Code I tried**
for (let i = 0; i < sim.header.length; i++) {
if (Object.keys(sim[i].header) === Object.keys(columns[i].header)) {
sim[i].header[columns[i].header.FIELD_DESC] = sim[i].header[Object.keys(sim[i].header)]
}
}
console.log(sim);
Expected Output:
output = {
"header": [{
"Sales Organization": "1000",
"Distribution Channel: "
10 "
},
{
"Sales Organization": "1000",
"Distribution Channel": "20"
}
]
}
Is not perfect but try this
let sim = {
"header": [
{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
};
let columns = [
{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
];
const filter = {};
for (let i = 0; i < columns.length; i++) {
filter[columns[i].FIELD] = columns[i].FIELD_DESC;
}
sim.header = sim.header.map(el => {
const keys = Object.keys(el);
const newObj = {}
for (const key of keys) {
newObj[filter[key]] = el[key];
}
return newObj;
});
console.log(sim);
Here is an approach using Map and array.map . We store the columns as key value pair in Map , then while traversing the sim.header , just get the value from the map for the particular key and update it .
let sim = {
"header": [{
"VKORG": "1000",
"VTWEG": "10"
},
{
"VKORG": "1000",
"VTWEG": "20"
}
]
}
let columns = [{
"FIELD": "VKORG",
"FIELD_DESC": "Sales Organization"
},
{
"FIELD": "VTWEG",
"FIELD_DESC": "Distribution Channel"
}
]
var map = new Map();
columns.forEach(obj => {
map.set(obj.FIELD, obj.FIELD_DESC);
})
sim.header = sim.header.map(obj => {
var tempObj = {};
Object.keys(obj).forEach(key => {
tempObj[map.get(key)] = obj[key]
})
return tempObj;
})
console.log(sim);
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);
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);
Here I need to convert my nested JSON into a custom JSON without having nested objects.
function transform(){
let items = [
{
"carId":328288,
"firstName":"yathindra",
"lastName":"rawya",
"list":[
{
"id":182396,
"isAvail":false,
"stateId":288,
"state":"Awesome"
},
{
"id":182396,
"isAvail":false,
"stateId":678,
"state":"Cool1"
}
],
},
{
"carId":3282488,
"firstName":"yathindraR",
"lastName":"K",
"list":[
{
"id":18232396,
"isAvail":false,
"stateId":22388,
"state":"Awesome"
},
{
"id":182356796,
"isAvail":false,
"stateId":45678,
"state":"Cool"
}
],
}
]
let customList = [];
for(let i=0;i<items.length;i++){
let temp = new Array()
for(let j=0;j<items[i].list.length;j++){
temp.push(
items[i].list[j].state
)
}
customList.push({
fname: items[i].firstName,
lname: items[i].lastName,
...temp
})
}
console.log(JSON.stringify(customList))
}
transform();
Below is the output I am getting.
[{"0":"Awesome","1":"Cool1","fname":"yathindra","lname":"rawya"},{"0":"Awesome","1":"Cool","fname":"yathindraR","lname":"K"}]
But I don't want to place items in the temp array in the beginning. I want them to place at last.
Something like this.
[{"fname":"yathindra","lname":"rawya","0":"Awesome","1":"Cool1"},{"fname":"yathindraR","lname":"K","0":"Awesome","1":"Cool"}]
Here there is no need of using numbers as keys in the temp array. Because I want only values of each. So its ok if the keys of all are strings and order of values matters. How to make this done?
Please replace your code with below one, it will work straight away.
Key will be "state-1", "state-2" instead of "0", "1"
function transform(){
let items = [
{
"carId":328288,
"firstName":"yathindra",
"lastName":"rawya",
"list":[
{
"id":182396,
"isAvail":false,
"stateId":288,
"state":"Awesome"
},
{
"id":182396,
"isAvail":false,
"stateId":678,
"state":"Cool1"
}
],
},
{
"carId":3282488,
"firstName":"yathindraR",
"lastName":"K",
"list":[
{
"id":18232396,
"isAvail":false,
"stateId":22388,
"state":"Awesome"
},
{
"id":182356796,
"isAvail":false,
"stateId":45678,
"state":"Cool"
}
],
}
]
let customList = [];
for(let i=0;i<items.length;i++){
let temp = {};
for(let j=0;j<items[i].list.length;j++){
temp["state-"+(j+1)] = items[i].list[j].state;
}
customList.push({
fname: items[i].firstName,
lname: items[i].lastName,
...temp
})
}
console.log(JSON.stringify(customList))
}
transform();
Javascript Object first shows the sorted number list and then, the rest of the object's content as it is! run the following code and see what happens:D
console.log(JSON.stringify({1:true, b:false, 3:false}))
So if you want to keep your order, don't use numbers as keys!
Prepend your key with a zero, and then insertion order is maintained. In a CSV, that seems a good option.
If you want to use the spread operator, use an object instead of an array.
function transform() {
let items = [{
"carId": 328288,
"firstName": "yathindra",
"lastName": "rawya",
"list": [{
"id": 182396,
"isAvail": false,
"stateId": 288,
"state": "Awesome"
},
{
"id": 182396,
"isAvail": false,
"stateId": 678,
"state": "Cool1"
}
],
},
{
"carId": 3282488,
"firstName": "yathindraR",
"lastName": "K",
"list": [{
"id": 18232396,
"isAvail": false,
"stateId": 22388,
"state": "Awesome"
},
{
"id": 182356796,
"isAvail": false,
"stateId": 45678,
"state": "Cool"
}
],
}
]
let customList = [];
for (let i = 0; i < items.length; i++) {
let temp = {}
for (let j = 0; j < items[i].list.length; j++) {
temp['0' + j] = items[i].list[j].state
}
const o = {
fname: items[i].firstName,
lname: items[i].lastName,
...temp
}
customList.push(o)
}
console.log(JSON.stringify(customList))
}
transform();
That said, there are other ways you can map your items...
function transform() {
let items = [{
"carId": 328288,
"firstName": "yathindra",
"lastName": "rawya",
"list": [{
"id": 182396,
"isAvail": false,
"stateId": 288,
"state": "Awesome"
},
{
"id": 182396,
"isAvail": false,
"stateId": 678,
"state": "Cool1"
}
],
},
{
"carId": 3282488,
"firstName": "yathindraR",
"lastName": "K",
"list": [{
"id": 18232396,
"isAvail": false,
"stateId": 22388,
"state": "Awesome"
},
{
"id": 182356796,
"isAvail": false,
"stateId": 45678,
"state": "Cool"
}
],
}
]
let customList = items.map(item => {
let j = 0;
let list = item.list.reduce((acc, it) => {
acc['0' + j++] = it.state;
return acc
}, {})
return {
fname: item.firstName,
lname: item.lastName,
...list
}
})
console.log(JSON.stringify(customList))
}
transform();