Updating the values in map in javascript - javascript

Trying to update the values in a map in javascript. Below is how my map looks like.
Data in Map :[{…}]
[{
accId: "001",
lineOfBusiness: "Protection",
name: "Ins",
plannedValue: 1200.18,
SellOutValue: 4115.85,
productGroup: "INS",
sesnId: "a2s",
subGroups: [{
accountId: "001",
brandName: "INS",
isLocked: true,
lineOfBusiness: "Ction",
name: "Ins",
portfolioId: "a34",
productGroup: "IDES",
recordId: "006",
seasonId: "a2s",
territoryId: "0MI",
unitOfMeasurement: "MXN"
}]
}]
Here i am trying to update the map values plannedValue and SellOutValue with the updated values in a new map. when i am executing the below code i am getting the error
set is not a function.
//Cloning the map and formatting the values
let map1 = {};
for(var i in incoming){
map1[i] = incoming[i]
map1[i].set('plannedValue',map1[i].plannedValue.toLocaleString())
map1[i].set('SellOutValue',map1[i].SellOutValue.toLocaleString())
}
console.log(map1);
can someone please help me on this

map[i] is an object (an element of the incoming Map), not a Map. So use ordinary property access.
map[i].plannedValue = map1[i].plannedValue.toLocaleString();
map[i]. SellOutValue = map1[i].SellOutValue.toLocaleString();
Note that you're not making clones of the objects in the Map, so this will modify the original objects as well.

Related

combining javascript object property value and display

Hi I am having difficulty in traversing in javascript object. How can I get scheme_name & NAV from both and store it in variable like "You have 2 schemes linked to your account. scheme_name1 NAV value is "" scheme_name2 NAV value is "" and so forth. Please explain it to me thanx
let data = [{
"CustomerID": 12345,
"NAV": "95.24059718",
"cost_of_purchase": 799900,
"folio_number": 10007060,
"id": 1,
"mutual_fund_house": "AXIS MUTUAL FUND",
"no_of_units": 15000,
"option": "GROWTH",
"plan": "REGULAR",
"resource_uri": "/api/v1/folio/1/",
"scheme_name": "AXIS LONG TERM EQUITY",
"value_of_units": "1428608.9580"
}, {
"CustomerID": 12345,
"NAV": "1053.31517400",
"cost_of_purchase": 1500000,
"folio_number": 5540000567,
"id": 2,
"mutual_fund_house": "SBI Mutual Fund",
"no_of_units": 2750,
"option": "DIVIDEND",
"plan": "DIRECT",
"resource_uri": "/api/v1/folio/2/",
"scheme_name": "SBI Magnum Multicap Fund",
"value_of_units": "2896616.7270"
}]
It looks like you try to map that object to another object.
First, try to read and understand array methods, you can check:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
And for map method you can check:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
And as a specific answer you can do:
const mappedData = data.map(function(item) {
return {
scheme_name: item.scheme_name,
NAV: item.NAV
};
});
This will return you an array of a simplified version of yours.
After that, you can convert it to a string like:
let solution = `You have ${mappedData.length} schemes linked to your account. `;
mappedData.forEach(function(mapped) {
solution += mapped.scheme_name + ' is ' + mapped.NAV + ' '
});
Note: I showed map method for giving an insight about what you can do, normally you don't need to simplify, you can directly use for each version.
Imagine each one of your objects (in this case you have provided two (2)) as an associative array inside of an array. Meaning that rather than reference it by it's index position, you can reference it by it's key.
This means to access object 1, you would have to write data[0]. But if you alerted this, this would simply tell you that data[0] is an object. Which is is.
To access an actual value in that array, you would then have to provide the key, which you can do by providing a number, or in your case perhaps more easily, it's associated key, which is "scheme_name".
See the following :
let data = [{
"CustomerID": 12345,
"NAV": "95.24059718",
"cost_of_purchase": 799900,
"folio_number": 10007060,
"id": 1,
"mutual_fund_house": "AXIS MUTUAL FUND",
"no_of_units": 15000,
"option": "GROWTH",
"plan": "REGULAR",
"resource_uri": "/api/v1/folio/1/",
"scheme_name": "AXIS LONG TERM EQUITY",
"value_of_units": "1428608.9580"
}, {
"CustomerID": 12345,
"NAV": "1053.31517400",
"cost_of_purchase": 1500000,
"folio_number": 5540000567,
"id": 2,
"mutual_fund_house": "SBI Mutual Fund",
"no_of_units": 2750,
"option": "DIVIDEND",
"plan": "DIRECT",
"resource_uri": "/api/v1/folio/2/",
"scheme_name": "SBI Magnum Multicap Fund",
"value_of_units": "2896616.7270"
}]
for (let i = 0; i < data.length; i++) {
alert(data[i]["scheme_name"]);
}
So quite simply, for i = 0, with i being less than the number of associative arrays in your array named data, alert the value on that indexed array, by the associated key.
You've got an array of data so firstly you need to iterate through that array.
Pick which properties you want to keep per record, and save them to a results array.
Once you have the results you can iterate through them and print out your individual records.
let data = [{"CustomerID":12345,"NAV":"95.24059718","cost_of_purchase":799900,"folio_number":10007060,"id":1,"mutual_fund_house":"AXIS MUTUAL FUND","no_of_units":15000,"option":"GROWTH","plan":"REGULAR","resource_uri":"/api/v1/folio/1/","scheme_name":"AXIS LONG TERM EQUITY","value_of_units":"1428608.9580"},{"CustomerID":12345,"NAV":"1053.31517400","cost_of_purchase":1500000,"folio_number":5540000567,"id":2,"mutual_fund_house":"SBI Mutual Fund","no_of_units":2750,"option":"DIVIDEND","plan":"DIRECT","resource_uri":"/api/v1/folio/2/","scheme_name":"SBI Magnum Multicap Fund","value_of_units":"2896616.7270"}]
let results = []
data.forEach(datum => {
results.push({
scheme_name: datum.scheme_name,
nav: datum.NAV,
})
})
console.log(`You've got ${results.length} items in your account.`)
results.forEach(result => {
console.log(`${result.scheme_name} - NAV value is: ${result.nav}`)
})
I created sample fiddle for you. You need to iterate over each object in your main object and store all information outside.
data.forEach(function(item) {
console.log(item.scheme_name);
});

How to add key value pair as last entry in OrderedMap..?

Possible duplicate:
Add an Item in OrderedMap with Immutable.js
Working with redux store and Immutable js OrderedMap.
Redux store structure:
{
"app": {
"name": "Test app",
"dataPack":{
"chemID": "aaaa",
"item": {
"yp57m359": {
"solid": 33,
"liquid": 45,
"gas": 65
},
"h58wme1y": {
"solid": 87,
"liquid": 9,
"gas": 30
},
"dff56fhh": {
"solid": 76,
"liquid": 43,
"gas": 77
}
}
}
}
}
Reducer code:
return state.setIn(["app","dataPack","item",action.item_id],
fromJS({
"solid": action.soildVal,
"liquid": action.liquidVal,
"gas": action.gasVal
}));
where action.item_id is the random id (key for every item).
Above code works perfectly for adding items.
Problem is: Items stored in a random position. I need to keep the order I am adding. Need to add every item as last entry inside item. Adding one by one item is not in same order.
Help me to get a clear solution for this.
An OrderedMap will remember the order you put things in it. Every time you call .set(key, value) with a new key on an OrderedMap, it will get added to the end.
let state = Immutable.Map({
"app": Immutable.Map({
"name": "Test App",
"dataPack": Immutable.Map({
"chemId": "aaaa",
"items": Immutable.OrderedMap({}) // this is the thing we want ordered
})
})
});
state = state.setIn(['app', 'dataPack', 'items', 'yp57m359'], Immutable.Map({
'first': 'item'
}));
state = state.setIn(['app', 'dataPack', 'items', 'h58wme1y'], Immutable.Map({
'second': 'item'
}));
state = state.setIn(['app', 'dataPack', 'items', 'dff56fhh'], Immutable.Map({
'third': 'item'
}));
console.log(state.toJS()); // notice things are in order
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
It's hard to tell exactly where your problem is because we can't see how you created your store, but my guess would be that "item" is pointing to a regular old Map instead of an OrderedMap. If you're just using fromJS(data) to create your state, it will default to using a Map instead of an OrderedMap.

Vue js - reference variable in object

I am new to vue and can't find a solution to this -
I have a JSON object here, and I am trying to dynamically fetch the "info" of a user based on their "userRegion".
{
"userData": {
"kr": {
"info": {
"name": "testing-123",
}
},
"any": null,
"us": null,
"eu": {
"info": {
"name": "testing-456",
}
},
},
"userRegion": "eu"
}
I then have this object in vue and I want to dynamically change region and pull the data from the object based on this region value in the "user" object below.
user:{
region: this.userData.userRegion,
name: this.userData[this.user.region].info.name
},
For example, I have tried using something like this
this.userData.userData[this.user.region]
but I get an error:
TypeError: Cannot read property 'region' of undefined"
the variable I am using "userData" is passed down from the parent like so:
<infoWindow :userData='userData'></infoWindow>
and is set as a prop:
props: {
userData: app.userData,
},
any help would be aprpeciated, thanks
I don’t really understand where you are setting this user, whether its part of an initialized data object, or a computed property. However, there is a temporal issue there:
user: {
region: this.userData.userRegion,
name: this.userData[this.user.region].info.name
},
In order to set up user.name, user.region needs to be already there. But since you are creating the user object at once, this does not work. So you either have to split that up, or repeat the logic for the user region again:
user: {
region: this.userData.userRegion,
name: this.userData[this.userData.userRegion].info.name
},

Use array value to find parent object's key value

Using Google's Maps API, I want to be able to find the value of a key within an object by the value within an array within the same object. When I "Inspect Element" on my page in order to view the console, here is what it shows in terms of object structure:
results: {
address_components [
0: Object: {
long_name: "704",
short_name: "704",
types [
0:"street_number"
]
}
1: Object {...}
2: Object {...}
3: Object {...}
]
place_id:"8AS8D8F8A881C81DA6S6D8"
}
I want to be able to find "street_number" in the object so I can find the corresponding value of "704" that also resides in the object.
The tricky part is that the values within "address_compenents" are not always in the same order so I cannot just write results[0].address_components[0].long_name in my javascript to find it. I am restricted to javascript in this project so any answers in that language would be much appreciated. Thank you in advance!
Note: I am not opposed to using libraries like lodash or underscore if it helps solve the problem.
First find() the item, then read the required attribute.
Note that you should also think about and handle the case where there is no street_number in the response, which is not covered by this snippet.
var results = {
address_components: [{
long_name: "704",
short_name: "704",
types: [
"street_number"
]
}, {
long_name: "100",
short_name: "100",
types: [
"attribute_a"
]
}, {
long_name: "200",
short_name: "200",
types: [
"attribute_b"
]
}, {
long_name: "300",
short_name: "300",
types: [
"attribute_c"
]
}],
place_id: "8AS8D8F8A881C81DA6S6D8"
}
var streetNumber = results.address_components.find(function(item) {
return item.types.some(function(subitem) {
return subitem === 'street_number'
});
}).long_name;
console.log(streetNumber); // 704
it is possible to do it by using Array.filter()
results: {
address_components [
0: Object: {
long_name: "704",
short_name: "704",
types [
0:"street_number"
]
}
1: Object {...}
2: Object {...}
3: Object {...}
]
place_id:"8AS8D8F8A881C81DA6S6D8"
}
const result = results.address_components.find(item => item.types.indexOf('street_number') > -1)
const longName = result.long_name // 704
const shortName = result.short_name // 704

Nested JSON Objects with Dimple.js

I'm attempting to create a stacked bar chart with Dimple.JS and D3. However, the JSON file I wish to use with this particular visualization involves nested JSON objects (below). The stacked bar chart I wish to create has the channel category as its x-axis, with the y axis to be the aggregate count of the different locations (with each location as a 'stack'). Here is the original data:
[{
"channel": "politics",
"locations":
[{
"name":"usa",
"count" : 1454
},
{
"name":"mexico",
"count":3543
},
{
"name":"antarctica",
"count":4352
}]
},
{
"channel": "economics",
"locations":
[{
"name":"usa",
"count" : 12431
},
{
"name":"mexico",
"count":314
},
{
"name":"china",
"count":2321
}]
}]
I've flattened the above into the JSON below, but I am having trouble using Dimple's .addSeries() method to create the stack.
[
{
"channel": "politics",
"locations[0].name": "usa",
"locations[0].count": 1454,
"locations[1].name": "mexico",
"locations[1].count": 3543,
"locations[2].name": "antarctica",
"locations[2].count": 4352
},
{
"channel": "economics",
"locations[0].name": "usa",
"locations[0].count": 12431,
"locations[1].name": "mexico",
"locations[1].count": 314,
"locations[2].name": "china",
"locations[2].count": 2321
}
]
My question is this: how can Dimple support either this data encoded in this particular JSON file? Most samples use CSV and TSV files, but I unfortunately have the limit of using only JSON files.
Dimple can't use nested data. You'll have to flatten it on the client side so there's a single JSON object for each intersection of channel/location. Here's an example of how to do that with Underscore.js :
var chartData = _.chain(data)
.map(function(row, index){
// for each original row, return a new row for each location
return _.map(row.locations, function(location){
return {
'channel' : row.channel,
'name' : location.name,
'count' : location.count
};
});
})
.flatten()
.value();
(For every row in the original data set, it will return three rows, one for each location. This will return an array of nested arrays, so it calls flatten to make the whole array 1 level deep.)
Here's a jsBin showing that in action : http://jsbin.com/nuvihu/edit?html,js,output
(output):
If this helps, here is what the data ended up looking like :
[{"channel":"politics","name":"usa","count":1454},{"channel":"politics","name":"mexico","count":3543},{"channel":"politics","name":"antarctica","count":4352},{"channel":"economics","name":"usa","count":12431},{"channel":"economics","name":"mexico","count":314},{"channel":"economics","name":"china","count":2321}]

Categories

Resources