Javascript - How to access object - javascript

I have an object with store in this variable report[sales] which contain information such as all, amount, month as an object.
When i tried to console log the following console.log(report[sales]), i received the result of {All: 1, amount: 855, month: 2}.
But when i want to access the value for All which I tried the following report[sales].All the result is undefined and I also tried report[sales]["All"].
** Edit **
Result of console.log(report)
{Feb: {All: 1, amount: 855, month: 2, …}}
Result of console.log(report[sales])
{All: 1, amount: 855, month: 2, …}
I want to access value of All

Try this
const report = {
sales: {All: 1, amount: 855, month: 2}
}
console.log(report.sales.All);

Just try console.log(report.sales.All); it will work

Thanks for adding the text to your question. I have no idea where you got sales from based on the info you provided, but below is a couple examples on how to log out the value of All. Another thing, you stated that report is an array, however it actually is an object based on your console.log in your question.
let report = {Feb: {All: 1, amount: 855, month: 2}, March: {All: 2, amount: 855, month: 2}}
// Just log out the Feb.All value
console.log(report.Feb.All);
// A for in loop is an easy way to loop over objects
for(let i in report) {
// This will log out all the All values in the object.
// Just swap out All with amount or month to print the other values.
console.log('All = ' + report[i].All);
}

Related

Use For loop to iterate through array of objects to get the greatest Balance

const bankAccounts = [
{
id: 1,
name: "Susan",
balance: 100.32,
deposits: [150, 30, 221],
withdrawals: [110, 70.68, 120],
},
{ id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
{
id: 3,
name: "Joshua",
balance: 18456.57,
deposits: [4000, 5000, 6000, 9200, 256.57],
withdrawals: [1500, 1400, 1500, 1500],
},
{ id: 4, name: "Candy", balance: 0.0 },
{ id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];
function getClientWithGreatestBalance(bankAccounts) {
const maxAccount = bankAccounts[0];
const newArr = [];
for (let i = 0; i < array.length; i++) {
if (bankAccounts[i].balance > maxAccount.balance)
newArr.push([i]);
}
return newArr;
}
I am trying to loop through the bankAccounts array to get the object that has the greatest balance and push that object into the new array and return that single account.
I know I need to check the balance of each account but for some reason can not figure out how to get the single object.
I guess that array variable you are using in the for loop is meant to be bankAccounts, and at first it seemed weird to me that you are returning an array then I thought that you may have wanted to return an array in case there are multiple accounts that share the max balance. So, with that in mind your function should be something like this
function getClientWithGreatestBalance(bankAccounts) {
let maxBalance = 0;
let maxBalanceAcounts = [];
for (let i = 0; i < bankAccounts.length; i++) {
if (bankAccounts[i].balance > maxBalance){
maxBalance = bankAccounts[i].balance;
maxBalanceAcounts = [];
maxBalanceAcounts.push(bankAccounts[i])
}
else if (bankAccounts[i].balance === maxBalance){
maxBalanceAcounts.push(bankAccounts[i])
}
}
return maxBalanceAcounts;
}
You can't know which is the biggest until you've seen all of them, so it doesn't make sense to push anything to your output array until the end.
Instead, you need to keep track of the account with the biggest balance of those you've seen so far. So instead of an array, you want a single variable to track that one.
In fact you already have that variable, maxAccount. So if you find an account with a bigger balance than maxAccount.balance, you want to set maxAccount to the new account, instead of the previous max.
Once you have finished the loop, then you can push that to your output array (assuming you even need an output array, since you are always just returningg one).
Other points about your code:
getClientWithGreatestBalance will crash if you give it an empty input array.
You are starting by assuming (temporarily) that the first account is the biggest - which is OK, but then you are starting a loop at the first account, so the first time round the loop is comparing the first account to itself, which is unnecessary (but won't cause any errors).
It's better to iterate over an array directly rather than by index. Again, your code isn't wrong in that respect, but over-complicated.
for (let account of array) {
// ...
}

How to sort an object array by browsing by week?

I would like to sort and modify the output of an object array by browsing week by week from the earliest date, to sort by week the sum of qt.
Datas: [
{qt: 3, date: 03-03-2020},
{qt: 2, date: 02-14-2020},
{qt: 4, date: 13-03-2020},
{qt: 3, date: 04-02-2020},
]
Desired result:
[
week1: 3,
week2: 6,
week3: 0,
week4: 0,
week5: 3
]
I’ve been trying to turn it all up since yesterday, but I'm starting to have a lot of trouble. I'm working on React with Akita. If you have possible algorithm orientations, I am interested.
You can use lodash library.
var _ = require('lodash');
const ordered = _.orderBy(Datas, 'date', 'asc');
it sort your Datas according to date by ascending.I realize that you want erroneous form as desired result you cannot make it [week1: 3] it should be [{week1:3}] but it doesn't matter. You should make a list [3,6,0,0,3] and assume that their indexes represent their week number.So following code gives you the list:
const desiredResult = ordered.map(obj => {
return obj.qt;
});
Also you may want visit this website to learn how to install lodash
The difficulty is above all to travel PER WEEK in a date range (the oldest to that of today). It is a question of isolating even in the first emps to obtain:
[{
week1: {qt: ..., date: ...}, //week1 = date range between Monday and Sunday
week2: {qt: ..., date: ...},
...]

Combine objects of an array with the same date into one - JavaScript

I receive an array of posts through an API and want to merge the ones with the same "month" and "year" (day is not important), into one object. I looked up for answers but there are just too many foo-bar examples that confuses more than helping. I want to know the cleanest, most elegant way of handling such problems, without getting into call-back hell and nested blocks...
Here is the API response:
0:
{
date: {day: 27, month: 1, year: 2020}
id: 3
}
1:
{
date: {day: 28, month: 1, year: 2020}
id: 4
}
2:
{
date: {day: 31, month: 1, year: 2020}
id: 5
}
3:
{
date: {day: 1, month: 2, year: 2020}
id: 6
}
4:
{
date: {day: 2, month: 2, year: 2020}
id: 7
}
The expected outcome:
0:
result: {month: 1, year: 2020, id:[3,4,5]}
1:
result: {month: 2, year: 2020, id:[6,7]}
One approach would be to use the Array#reduce() method to transform the input array into a dictionary, where each value contains the accumulation of id's for that month and year. Once this dictionary has been built, you could then extract the values of that dictionary to an array via Object#values() to obtain the required output:
let input=[{date:{day:27,month:1,year:2020},id:3},{date:{day:28,month:1,year:2020},id:4},{date:{day:31,month:1,year:2020},id:5},{date:{day:1,month:2,year:2020},id:6},{date:{day:2,month:2,year:2020},id:7}];
/* Convert the dictionary that will be created by reduce to a value array */
var output = Object.values(input.reduce((dict, item) => {
const { date, id } = item;
/* The distinct key for this item based on month/year of date field */
const key = `${date.month}-${date.year}`;
/* Check if dictionary already has an object value for key. This short hand
will only insert a new object value for key, if one does not already exist
in the dictionary */
const value = dict[key] || { month : date.month, year : date.year, id : [] };
/* Add the item id to the dictionary entries id array */
value.id.push(id);
/* Update value object for key */
return { ...dict, [key] : value };
}, {}))
console.log(output);
The idea here is that the dictionary is built using Compound Keys, where the keys are derived from the month and year of the current array item.
When no value exists for the current key, a new value object is inserted to the dictionary for that key:
{ month : date.month, year : date.year, id : [] }
The id of the current array item is then added (accumulated) to the id sub array of the object for that key:
dict[key].id.push(id);
Hope that helps
Here is an alternate approach, if you are not a big fan of Array.reduce and Array.values and also, if you like to consider performance when running the response for a larger data set.
This approach avoids cloning object (or rather non-mutating object) with spread operator i.e {...<anyObject>} while iterating. which should be fine for minimal set of data but but definitely not when you deal with huge volume.
const response = [{
date: { day: 27, month: 1, year: 2020 },
id: 3
}, {
date: { day: 28, month: 1, year: 2020 },
id: 4
}, {
date: { day: 31, month: 1, year: 2020 },
id: 5
},{
date: { day: 1, month: 2, year: 2020 },
id: 6
},{
date: { day: 2, month: 2, year: 2020 },
id: 7
}];
function groupByMonthYear(response) {
// output
const groupedData = []
// Using map for lookup to avoid iterating again on the grouped data
const referenceMap = new Map();
// destructing month, year and id from the response
for (const { date: { month, year }, id } of response) {
const groupKey = `${month}${year}`
// check if the month and year reference is already seen using the groupKey MMYYYY
if (referenceMap.has(groupKey)) {
referenceMap.get(groupKey).id.push(id);
// early return
continue;
}
// simply add a new entry if it doesn't exist
const data = {
month,
year,
id: [id]
};
groupedData.push(data);
referenceMap.set(groupKey, data)
}
return groupedData;
}
// Invoke and Print the result
console.log(groupByMonthYear(response));

Compare multiple objects in the array and sum values when a certain common value, JavaScript / Vue.js

This might be an easy task to solve for more experienced programmers. I have been searching for answers for a while but somehow I haven't found a solution yet. So, my problem is following.
There is an array of multiple objects, for example in my case:
const array = [
{Id: 0, Name: 'John', Currency: 'USD', Amount: 25},
{Id: 1, Name: 'Matt', Currency: 'EUR', Amount: 460},
{Id: 2, Name: 'Lisa', Currency: 'YEN', Amount: 60000},
{Id: 3, Name: 'Pete', Currency: 'EUR', Amount: 2400}
]
As you can see, there are similarities between the object values. In my case, I would like to have a solution where all the same currencies and their values are combined::
(e.g. Currency: 'EUR' (obj1 & obj2), Amount: 460 (obj1) + 2400 (obj2) = 2860)
So, the final result would look something like this:
const finalarray = [
{Currency: 'USD', Amount: 25},
{Currency: 'EUR', Amount: 2860},
{Currency: 'YEN', Amount: 60000}
]
I personally, don't mind if the other keys of the object don't exist in the final array, as long as:
1) The objects of the array compare one of their values with all the other values of the same key, and
2) The amounts with the value of a certain same key are combined with each other, all of them.
I'm working with a Vue.js project, so I need the language to be JavaScript. What comes to the answer, the simpler the better as I'd like to keep the code as compact as possible. But the most important thing is that it solves the problem. I'm having a Computed property currencyList() that is going to return the new array.
Thank you in advance!
A very quick solution I thought of was:
const accumulator = (array) => array.reduce((res, item) =>
res.set(item.Currency, (res.get(item.Currency)||0) + item.Amount), new Map());
const values = Array.from(accumulator(array), item => ({item[0]: item[1]}))
The cost is O(n) So thats fine. you can probably prettify it

Remove Duplicates from my collection in meteorjs app && render the recent score of each player

I am working on a Meteorjs application which is using MongoDB in back end. In my collection there are some a lot of duplicates data like ( just an example)
{name:'A',score: 2, date: 4456546}
{name:'A',score:33, date:3453454}
{name:'A',score:34, date: 3453}
{name:'A',score:0, date: 12334}
{name:'B',score: 2, date: 4456546}
{name:'B',score:33, date:3453454}
{name:'B',score:34, date: 3453}
{name:'B',score:0, date: 12334}
{name:'C',score: 2, date: 4456546}
{name:'C',score:33, date:3453454}
{name:'C',score:34, date: 3453}
{name:'C',score:0, date: 12334}
I want to copy all this collection on an array, remove duplicates names and save only the name and the recent score of each player, like this for example
{name:'A',score: 2, date: 4456546}
{name:'B',score: 2, date: 4456546}
{name:'C',score: 2, date: 4456546}
for this I try $puch with update method but does not work;
have you any idea how to solve this??
thak's for help
It's not entirely clear what you're trying to do but you can use underscore's uniq function to find unique values. In the example below I've used sort to sort the values highest date to lowest. Next I've used the uniq function with a iteratee function which returns the name as the value to check for uniqueness.
var allScores = [
{name:'A',score: 2, date: 4456546},
{name:'A',score:33, date:3453454},
{name:'A',score:34, date: 3453},
{name:'A',score:0, date: 12334},
{name:'B',score:34, date: 3453},
{name:'B',score:0, date: 12334},
{name:'B',score: 2, date: 4456546},
{name:'B',score:33, date:3453454},
{name:'C',score:33, date:3453454},
{name:'C',score: 2, date: 4456546},
{name:'C',score:34, date: 3453},
{name:'C',score:0, date: 12334}
];
var latestScores = _(allScores).chain().sort(function(a,b){return (b.date - a.date)}).uniq(function (x){ return x.name }).value();
// latestScores equals [{name:'A',score: 2, date: 4456546},{name:'B',score: 2, date: 4456546},{name:'C',score: 2, date: 4456546}]
You'd have to deal with updating the database yourself. Best to make a backup first.

Categories