JavaScript: creating a map that maps multiple keys to a value? - javascript

I have a list of keys and a value. For example:
keys = ["keyA", "keyB", "keyC"];
value = 100;
I'm trying to create a function to create a map so that:
map["keyA"]["keyB"]["keyC"] = 100;
I assumed this was the best data structure based on the answer given here:
Anyway, the part that challenges me is that I need a function that will create a map for any number of keys. I've tried doing this in a loop but can't get it to work because I don't know how to access different levels of my map, but it also feels sloppy:
for(var i=0; i<keys.length; i++){
for(var j=0; j<i; j++){
maps[keys[0]]...[keys[j]] = {};
if(j+1 === i){
maps[keys[0]]...[keys[j]][keys[i]] = value;
}
}
}
How can I create my map?

You can try to store a reference to the last created inner object, and go deeper in a loop, in order to make it in a linear time:
// Input data:
var keys = ["keyA", "keyB", "keyC", "keyD", "keyE"];
var value = 100;
// Algorithm:
var result = {};
var last = result;
for (var i = 0; i < keys.length - 1; i++)
{
last = (last[keys[i]] = {});
// can be change to a two-liner:
// last[keys[i]] = {};
// last = last[keys[i]];
}
last[keys[keys.length - 1]] = value;
// Output:
document.body.innerHTML = JSON.stringify(result);
document.body.innerHTML += "<br/><br/>" + result["keyA"]["keyB"]["keyC"]["keyD"]["keyE"];

If you do not want to maintain a hierarchy of objects, I would suggest you concatenate the keys and store the value with the concatenated string as key.
This assumes you always have the same keys array. If your keys array is supplied externally, you can sort before joining.
See the snippet.
var keys = ["keyA", "keyB", "keyC", "keyD", "keyE"];
var value = 568;
var datastructure = {};
datastructure[keys.join("-")] = value;
document.getElementById("output").innerHTML = datastructure[keys.join("-")];
<span id="output"></span>

Assuming this structure is to be a tree where the nesting has arbitrary depth, first you might benefit from a helper function that lets you access possible non-existent paths safely:
function path(obj, str) {
return str.split('.').reduce(function (acc, key) {
return acc instanceof Object ? acc[key] : undefined;
}, obj);
}
And you also want a way to set such paths neatly:
function setPath(obj, str, val) {
var path = str.split('.');
var key = path.pop();
var target = path.reduce(function(acc, key) {
return acc[key] = acc[key] instanceof Object ? acc[key] : {};
}, obj);
target[key] = val;
}
Then you have a clean interface for storing and retrieving this data.
map = {};
setPath(map, 'keyA.keyB.keyC', 100);
path(map, 'keyA.keyB.keyC') // 100;
path(map, 'keyA.keyX.keyY') // undefined;
If you prefer, you could have it take arrays of keys instead of dot-notation paths as shown here (just omit the split steps).
Note that if you are never interested in accessing nodes in the tree other than the leaves, or wish to be able to have values for both map.a.b and map.a, you can do this much more simply by having a single depth:
map[keys.join('.')] = 100;
And since you've added in a comment that the objective here is actually just to associate a value with a set of keys, and that there is no actual tree structure at all:
function get(map, keys) {
var key = keys.sort().join('.');
return map[key];
}
function set(map, keys, val) {
var key = keys.sort().join('.');
map[key] = val;
}
If periods are plausible characters in your keys, substitute a different character that you can safely reserve.

Edit 24/12/2022
I have created an ES module for order agnostic multi map. I will explain here how you can set it up for the OP's use case.
https://github.com/martian17/ds-js
First you will want to clone the repository to your project, or copy the code.
$ git clone https://github.com/martian17/ds-js.git
Here is an example use case
// import it to your project
import {OrderAgnosticMultiMap} from "path_to_ds-js/multimap.mjs";
// Instantiate
const map = new OrderAgnosticMultiMap();
// Register values
map.set("keyA", "keyB", "keyC", "content 1");
map.set("keyA", "keyC", "keyC", "content 2");
map.set("keyA", "keyB", "keyB", "content 3");
// The keys can be any object
map.set(map, OrderAgnosticMultiMap, map, window, document, "content 4");
// Get values (keys can be in different orders)
console.log(map.get("keyB", "keyC", "keyA"));
// log: "content 1"
console.log(map.get("keyB", "keyB", "keyC"));
// log: undefined
map.set(document, map, window, OrderAgnosticMultiMap, map);
// log: "content 4"
// Check if a value exists for some keys
console.log(map.has("keyC", "keyC", "keyA"));
// log: true
console.log(map.has("keyA", "keyC", "keyA"));
// log: false
// Loop through values
for(let [tally,value] of map){
console.log(tally,value);
}
// log:
// Map(3) {"keyA" => 1, "keyB" => 1, "keyC" => 1} 'content 1'
// Map(3) {"keyA" => 1, "keyC" => 2} 'content 2'
// Map(3) {"keyA" => 1, "keyB" => 2} 'content 3'
// Map(3) {map => 2, OrderAgnosticMultiMap => 1, window => 1, document => 1} 'content 4'
// Delete keys
map.delete("keyC", "keyB", "keyA");
map.delete("keyB", "keyB", "keyA");
map.delete("keyC", "keyC", "keyA");
console.log(map.has("keyC", "keyC", "keyA"));
// log: false
Pre-edit
If there is anyone wondering if there is a solution for multi keyed ES6 map, here's my take.
The order does matter though, so map.get(a,b,c) and map.get(c,a,b) will fetch different values.
And you can of course use this as string to object map, so it satisfies the OP's use case as well.
class MultiMap{
map = new Map;
own = Symbol();// unique value that doesn't collide
set(){
let lst = [...arguments];
let val = lst.pop();
let map = this.map;
for(let k of lst){
if(!map.has(k))map.set(k,new Map);
map = map.get(k);
}
map.set(this.own,val);// to avoid collision between the same level
return val;
}
get(...lst){
let map = this.map;
for(let k of lst){
if(!map.has(k))return undefined;
map = map.get(k);
}
return map.get(this.own);
}
has(...lst){
let map = this.map;
for(let k of lst){
if(!map.has(k))return false;
map = map.get(k);
}
return map.has(this.own);
}
delete(...lst){
let map = this.map;
let maps = [[null,map]];
for(let k of lst){
if(!map.has(k))return false;
map = map.get(k);
maps.push([k,map]);
}
let ret = map.delete(this.own);
for(let i = maps.length-1; i > 0; i--){
if(maps[i][1].size === 0){
maps[i-1][1].delete(maps[i][0]);
}else{
break;
}
}
return ret;
}
}
Example use case
let a = {a:"a"};
let b = {b:"b"};
let c = {c:"c"};
let mm = new MultiMap;
//basic operations
console.log(mm.set(a,b,c,"abc"));// "abc"
console.log(mm.get(a,b,c));// "abc"
console.log(mm.has(a,b,c));// true
console.log(mm.delete(a,b,c));// true
// overlapping keys can be handled fine as well
mm.set(a,b,"ab");
mm.set(a,"a");
console.log(mm.get(a,b));// "ab"
console.log(mm.get(a));// "a"
For anyone curious about my use case: I was trying to make an event listener wrapper that maps to multiple events internally (mousedown => mousedown, touchstart etc). I needed to cache the arguments when .on() is called so .off() can find the right set of event listeners to remove.

Related

How to restart the numeration of the keys in a object?

What is the problem :
this are my data stored in this.state.jsondata :
{
label{0:1,1:1}
prediction{0:0,1:1}
text{0:"abc",1:"def"}
}
This comes front JSON.stringify(this.state.jsondata) :
{"label":{"1":0,"2":0,"3":0,"4":0},"text":{"1":"aa","2":"bb,"3":"cc","4":"dd"},"prediction":{"1":2,"2":2,"3":2,"4":2}}
when I delete one element using this code :
removeData = (keyToRemove) => {
// create a deep copy of the object
const clonedJsonData = JSON.parse(JSON.stringify(this.state.jsondata))
// now mutate this cloned object directly
Object.keys(clonedJsonData).forEach(key => delete clonedJsonData[key][keyToRemove])
// set the state
this.state.jsondata = clonedJsonData
this.state.jsondata becomes :
{
label{1:1}
prediction{1:1}
text{1:"def"}
}
instead of starting back to 0 like :
{
label{0:1}
prediction{0:1}
text{0:"def"}
}
So basically I want to set the key back to "0, 1, 2, 3.."
What have I tried :
I tried to iterate through my data but there is something wrong in it with the way I loop through it :
removeData = (keyToRemove) => {
// create a deep copy of the object
const clonedJsonData = JSON.parse(JSON.stringify(this.state.jsondata))
// now mutate this cloned object directly
Object.keys(clonedJsonData).forEach(key => delete clonedJsonData[key][keyToRemove])
// reset keys value
let i = 0
Object.keys(clonedJsonData).forEach(function(key) {
Object.keys(clonedJsonData[key]).forEach(function(k) {
var newkey = i++;
clonedJsonData[key][k] = clonedJsonData[key][k];
delete clonedJsonData[key][k];
})
})
// set the state
this.state.jsondata = clonedJsonData
}
What is the expected output ?
The expected output is :
{
label{0:1}
prediction{0:1}
text{0:"def"}
}
If your key basically represents the index of the value, why not using an array?
{ label: [1,1], prediction: [0,1], text: ["abc","def"] }
If you now delete the first entry in each array, data.text[0] will be "def" and so on...
Edit:
If you don't want to convert the data, you gotta be carefull, especially if you parse and stringify the whole thing around and then loop over the keys. They don't have to be in the same order afterwards.
Instead of cloning the object, deleting the key you want to remove and then updating all keys, you could also copy the object manually and leaving the key to remove out
var data = {label: {0:0, 1:0}, prediction: {0:0, 1:1}, text: {0:'abc',1:'def'}};
console.log("Original Data");
console.log(data);
removeData = (data, keyToRemove) => {
var ret = {};
Object.keys(data).forEach(key=>{
ret[key] = {};
let idx = 0;
for (let dataIdx = 0; dataIdx < Object.keys(data[key]).length; dataIdx++) {
if (dataIdx.toString() !== keyToRemove) {
ret[key][idx.toString()] = data[key][dataIdx.toString()];
idx++;
}
}
});
return ret;
}
var reducedData = removeData(data,"0");
console.log("Reduced Data");
console.log(reducedData);
Note that I don't loop over the keys, so I don't get the order mixed up.
Note that I also removed the side effects from your original function by handing over the data object as parameter.
So that's how I made it
removeData = (keyToRemove) => {
// create a deep copy of the object
const clonedJsonData = JSON.parse(JSON.stringify(this.state.jsondata))
// now mutate this cloned object directly
Object.keys(clonedJsonData).forEach(key => delete clonedJsonData[key][keyToRemove])
// reset keys value
let i = 0
Object.keys(clonedJsonData).forEach(function eachKey(key) {
i = 0
Object.keys(clonedJsonData[key]).forEach(function eachKey(kkey) {
var newkey = i++;
clonedJsonData[key][newkey] = clonedJsonData[key][kkey];
});
delete clonedJsonData[key][i];
});
// set the state
this.state.jsondata = clonedJsonData
}

How to create and push values into an 3 dimensional array

I need help with making a 3-dimensional array, my objective is e.g:
Just for graphic illustration :-), see row below
[category: 1[subcategories: 1[subsubcategories: 1,2],2[subsubcategories: 3,4]]
In scenario above the user has selected:
category 1
subcategories: 1
subsubcategories: 1,2
subcategories: 2
subsubcategories: 3,4
I can then with these values create a string like: 1^1:1,2^2:3,4
Hope anyone understands :)
Use objects instead of arrays. When you use string indexes on array elements the array gets turned into an object and some of the array methods might not work properly afterwards. Why not just use an object from the beginning then.
WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results.
this is taken from https://www.w3schools.com.
Here is an example of how to use it:
// Object = {} instead of array = []
var myObject = {};
myObject['category'] = {1: {subcategories: {1:[1,2], 2: [3,4] }} };
// For example
var anotherObject = {};
anotherObject['category'] = {1: {}, 2: {}};
anotherObject['category'][1] = [1,2];
anotherObject['category'][2] = [3,4];
// Edit: example 3
// ---------------
// result from database JSON format
var resultFromDB = {"category": {"1": {"subcategories": {"1": {"subsubcategories": [1,2]}, "2": {"subsubcategories": [3,4] }}}} };
// example of building new object from input
var myNewObject = {};
var type;
// go through the first level
for(var index in resultFromDB)
{
// in case you needed this is how you would check type of input
type = typeof resultFromDB[index];
if((type === "object") && (type !== null)) // check if its an object
{
// set myNewObject[index] to new object
myNewObject[index] = {};
// go through second level
for(var subIndex in resultFromDB[index])
{
// set myNewObject[index][subIndex] as new object
myNewObject[index][subIndex] = {};
// go through third level
for(var subSubIndex in resultFromDB[index][subIndex])
{
// simply use an '=' to get all from that level
myNewObject[index][subIndex][subSubIndex] = resultFromDB[index][subIndex][subSubIndex];
}
}
}
}
console.log("This is the new object");
console.log(myNewObject);
console.log("\n");
console.log("This is the original object");
console.log(myNewObject);
// If you need to extract in multiple places you could make a function for quick access
function returnObject(incomingObject)
{
var myNewObject = {};
var type;
// ... copy paste here all the above code from example 3 except resultFromDB
return myNewObject;
}
// then just call it from anywhere
var theNewestObject = returnObject(resultFromDB);

checking if more elements of array have same value of key , if they have remove one?

so I've tried everything that i know. Using map and filter, prototypes. Didn't work. .
[{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}]
So what I want to achieve, is when i do ajax, with javascript, to check if two or more object have same value for type, if there is for example two or more bmw-s, remove others and and push just one object with bmw type. Hope i am clear enough.
Thanks in advance
function removeDuplicates(arr) {
var alreadyExist = {}; // hash object to keep track of elemnt that have already been encountered
var indexes = []; // array of indexes that will be removed
arr.forEach(function(o, i) { // for each object o in arr
if(alreadyExist[o.type]) // if the type of the object o at index i already exist
indexes.push(i); // mark its index i to be removed later
else // if not
alreadyExist[o.type] = true; // then mark the object as found so other ones will be removed
});
// for each index in the indexes array
for(var i = 0; i < indexes.length; i++)
arr.splice(indexes[i] - i, 1); // remove the object at that index ( - i because the array arr is continually changing. Its length decrease every time we remove an item)
}
var array = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"red","type":"bmw"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}];
removeDuplicates(array);
console.log(array);
don't remove elements, create a filtered Array:
var yourArray = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}];
var cache = {},
filteredArray = yourArray.filter(({type}) => type in cache? false: (cache[type] = true));
console.log(filteredArray);
It's non destructive, more performant and even simpler and shorter.
Edit: And even without modern features:
var filteredArray = yourArray.filter(function(item){
return item.type in this? false: (this[item.type] = true);
}, {/* the cache-object */}); //abusing `this` to pass the cache object
You can keep track of which types are already present in your array with an object, then only push into new array those that are not present:
var vehicles = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"red","type":"bmw"}, {"color":"black","type":"mercedes"}];
var uniques = [];
var types = {};
for (var i = 0; i < a.length; i++) {
if (!types[a[i].type]) { uniques.push(a[i]); }
types[a[i].type] = true;
}
//uniques = [{"color":"black","type":"bmw"},{"color":"gray","type":"golf"}, {"color":"black","type":"mercedes"}];

Javascript: how to dynamically create nested objects INCLUDING ARRAYS using object names given by an array

Very similar to this question:
Javascript: how to dynamically create nested objects using object names given by an array
Instead of calling
assign(obj, keyPath, value)
example of usage of the previously answer:
var accountinfo = {}
assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");
That will output:
accountinfo = {name: "", addressinfo: {zipcode:"90210"}};
Now, I'd like to support arrays... in the above example, I'd like to support multiple addressinfo per account. I'd like to say:
assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");
The result would be:
accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}
var regex = /\[([0-9]+)\]/ will show me the # inside the brackets, but I'm not sure how I'd have to iterate through each element in the array to make sure it exists (and create it if it doesn't).. and the difficult part, support this for each array element submitted as part of the function (I'd like to say :
assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");
Edit:
Figured it out.
function assign(obj, keyPath, value) {
keyPath = keyPath.split(‘.’);
lastKeyIndex = keyPath.length - 1;
var re = /^(.+?)\[*(\d+)*\]*$/;
for (var i = 0; i < lastKeyIndex; i++) {
key = keyPath[i];
var ind;
var middle = re.exec(key);
key = middle[1];
ind = middle[2];
if (ind) {
if (!(obj[key]))
obj[key] = [];
if (!(obj[key][ind]))
obj[key][ind] = {};
}
if (!(key in obj))
obj[key] = {};
if (ind)
obj = obj[key][ind];
else
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}

Declaring array of objects

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.
var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();
This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?
var sample = new Array();
sample[] = new Object();
I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
Depending on what you mean by declaring, you can try using object literals in an array literal:
var sample = [{}, {}, {} /*, ... */];
EDIT: If your goal is an array whose undefined items are empty object literals by default, you can write a small utility function:
function getDefaultObjectAt(array, index)
{
return array[index] = array[index] || {};
}
Then use it like this:
var sample = [];
var obj = getDefaultObjectAt(sample, 0); // {} returned and stored at index 0.
Or even:
getDefaultObjectAt(sample, 1).prop = "val"; // { prop: "val" } stored at index 1.
Of course, direct assignment to the return value of getDefaultObjectAt() will not work, so you cannot write:
getDefaultObjectAt(sample, 2) = { prop: "val" };
You can use fill().
let arr = new Array(5).fill('lol');
let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));
Will create an array of 5 items. Then you can use forEach for example.
arr.forEach(str => console.log(str));
Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.
After seeing how you responded in the comments. It seems like it would be best to use push as others have suggested. This way you don't need to know the indices, but you can still add to the array.
var arr = [];
function funcInJsFile() {
// Do Stuff
var obj = {x: 54, y: 10};
arr.push(obj);
}
In this case, every time you use that function, it will push a new object into the array.
You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use push as Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.
var samples = []; /* If you have no data to put in yet. */
/* Later, probably in a callback method with computed data */
/* replacing the constants. */
samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
/* or */
samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */
I believe using new Array(10) creates an array with 10 undefined elements.
You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):
var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });
Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
//making array of book object
var books = [];
var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
books.push(new_book);
new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
books.push(new_book);
console.log(books[0].id);
console.log(books[0].name);
console.log(books[0].category);
console.log(books[0].price);
// also we have array of albums
var albums = []
var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
albums.push(new_album);
new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);
console.log(my_albums[0].name);
console.log(my_albums[1].name);
This Example Works with me.
Snapshot for the Output on Browser Console
Try this-
var arr = [];
arr.push({});
const sample = [];
list.forEach(element => {
const item = {} as { name: string, description: string };
item.name= element.name;
item.description= element.description;
sample.push(item);
});
return sample;
Anyone try this.. and suggest something.
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
you can use it
var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
sample.push({})
OR
sample.push(new Object())
}
Using forEach we can store data in case we have already data we want to do some business login on data.
var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];
sample.forEach(function(item){
data.push(item);
})
document.write(data);
Example by using simple for loop
var data = [];
for(var i = 0 ; i < 10 ; i++){
data.push(i);
}
document.write(data);
If you want all elements inside an array to be objects, you can use of JavaScript Proxy to apply a validation on objects before you insert them in an array. It's quite simple,
const arr = new Proxy(new Array(), {
set(target, key, value) {
if ((value !== null && typeof value === 'object') || key === 'length') {
return Reflect.set(...arguments);
} else {
throw new Error('Only objects are allowed');
}
}
});
Now if you try to do something like this:
arr[0] = 'Hello World'; // Error
It will throw an error. However if you insert an object, it will be allowed:
arr[0] = {}; // Allowed
For more details on Proxies please refer to this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
If you are looking for a polyfill implementation you can checkout this link:
https://github.com/GoogleChrome/proxy-polyfill
The below code from my project maybe it good for you
reCalculateDetailSummary(updateMode: boolean) {
var summaryList: any = [];
var list: any;
if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList }
else {
list = this.state.chargeDefinitionList;
}
list.forEach((item: any) => {
if (summaryList == null || summaryList.length == 0) {
var obj = {
chargeClassification: item.classfication,
totalChargeAmount: item.chargeAmount
};
summaryList.push(obj);
} else {
if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) {
summaryList.find((x: any) => x.chargeClassification == item.classfication)
.totalChargeAmount += item.chargeAmount;
}
}
});
if (summaryList != null && summaryList.length != 0) {
summaryList.push({
chargeClassification: 'Total',
totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount
})
}
this.setState({ detailSummaryList: summaryList });
}
var ArrayofObjects = [{}]; //An empty array of objects.

Categories

Resources