Pushing an object into an object under a certain key - javascript

I'm trying to achieve the following Array/Object,
[
1:[{data:data},{data:data}]
]
How would this be achieved?
I got thus far,
var data = [];
data['1'] = {data:data}
but this just overwrites.

The notation [] is for making Arrays, {} is for making Objects.
See the following
const data = {}; // Initialize the object
data['1'] = []// Makes data={'1':[]}
data['1'].push({data: 'data'}) // Makes data = {'1':[{data:'data'}]}
OR
const data = []; // Initialize the Array
data.push([]) // Makes data=[[]]
data[0].push({data: 'data'}) // Makes data = [[{data:'data'}]]

If i get you right you want to push objects into an array inside of an hashtable ( which can be easily implemented using an object in javascript).
So we need an object first:
const lotteries = {};
Now before storing data, we need to check if the relating array exists, if not we need to create it:
function addDataToLottery(lottery, data){
if(!lotteries[lottery]){ //if it doesnt exist
lotteries[lottery] = []; //create a new array
}
//As it exists definetly now, lets add the data
lotteries[lottery].push({data});
}
addDataLottery("1", { what:"ever"});
console.log(lotteries["1"]));
PS: If you want to write it in a fancy way:
class LotteryCollection extends Map {
constructor(){
super();
}
//A way to add an element to one lottery
add(lottery, data){
if(!this.has(lottery)) this.set(lottery, []);
this.get(lottery).push({data});
return this;
}
}
//Create a new instance
const lotteries = new LotteryCollection();
//Add data to it
lotteries
.add("1", {what:"ever"})
.add("1", {sth:"else"})
.add("something", {el:"se"});
console.log(lotteries.get("1"));

Related

How do i append an array to an already existing state array?

Trying to implement pagination using react but cannot seem to figure out a way to append the new response to an already existing state variable.
I'm trying to implement a load more functionality wherein the data is appended to the list itself.
const handleLoadMoreClick = () => {
let tempObj = postparem;
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
getProductChildMenu(APIProductList, postparem);
setCopyMenu(...copyMenu, productChildMenu);
};
Currently the map function is running iterating over productChildMenu so it replaces the data but i want to append the data in productChildMenu to copyMenu.
I tried iterating over productChildMenu and pushing each element to copyMenu but it is coming out undefined or if i push it completely at once, it creates a 2d array which does not iterate in map correctly.
You must do the following to merge 2 objects into your state.
const handleLoadMoreClick = () => {
...
...
setCopyMenu({...copyMenu, ...productChildMenu});
};
You cannot do what you are doing with tempObject here:
let tempObj = postparem;
// this is wrong.
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
Even though you call the variable tempObj a "temporary object", it is not a new object. It is just a reference to the object stored in the variable postparem.
So your code is identical to the (equally wrong) postparem.pagenumber = postparem.pagenumber + 1.
Instead, you really have to create a new object:
let tempObj = {
...postparem,
};
and then you can either modify that, or already introduce your change on object creation.
That would look like
let tempObj = {
...postparem,
pagenumber: postparem.pagenumber + 1,
};
setPostparem(tempObj);
Or even a bit shorter:
setPostparem({
...postparem,
pagenumber: postparem.pagenumber + 1,
});

How to amend a new key to existing object using session storage

I have below piece of code
addToFilterCriteriaTree(componentData) {
let id = componentData.props.data.id;
this.state.filterCriteriaTree[id] = componentData.criteria;
}
Instead of state ,I want to create a object 'filterCriteriaTree' using setStorage and add a new key to it
I've changed the parameters since it's cleaner to supply only the data needed for the function to do it's job rather than the entire object.
addToFilterCriteriaTree(id, criteria) {
let currentFilterCriteriaTree = JSON.parse(sessionStorage.getItem('filterCriteriaTree')) || {};
currentFilterCriteriaTree[id] = criteria;
sessionStorage.setItem('filterCriteriaTree', JSON.stringify(currentFilterCriteriaTree);
}

What is the best way to realise "join" with JS objects?

I'm working with MeteorJS (aned MongoDB).
I have two collections :
events, with idEvent
eventsType, with idEventType (finite list of
type of events)
The link between two collections must be realized with idEvent == idEventType.
The goal is to have an array of events, with eventstype object associed.
This following code is functionnal, but I find it horrible... What did you think about ?
events() {
// Type of event
const eventsType = EventsType.find();
const eventsTypeArray = [];
eventsType.forEach((ev) => {
eventsTypeArray[ev.idEventType] = ev;
});
// List of events
const eventsList = Events.find();
const eventsListArray = [];
// Merge both data
eventsList.forEach((ev) => {
const evObj = ev;
evObj.type = eventsTypeArray[ev.idEvent];
eventsListArray.push(evObj);
});
return eventsListArray;
}
Thanks ! :D
You could map your eventsList and use Object.assign to enrich the original item :
eventsListArray = eventsList.map(ev => Object.assign({type: eventsTypeArray[ev.idEvent]}, ev))
Test run :
originalArray = [{a:"1"}, {a:"2"}];
dataMap = { "1": 10, "2": 100 };
mappedArray = originalArray.map(i=>Object.assign({b:dataMap[i.a]}, i));
console.log(originalArray);
console.log(mappedArray);
Result :
[{a:"1"}, {a:"2"}] //original array left untouched
[{a:"1", b:10}, {a:"2", b:100}] // mappedArray contains the extra data
I actually had a similar problem recently where I wanted to join data from two collections.
My solution was to create a new local collection (this is a collection that lives on the client only).
client:
const LocalEvents = new Mongo.Collection(null);
From there, instead of pushing your joined objects in to an array, you can join them and push the new objects in to the LocalEvents collection. This gives you the benefit of being able to query the new objects from the local minimongo collection. You'll need to make sure you clear the local collection when the template/component is destroyed. Also run a tracker function to empty the LocalCollection if your cursor changes.
Tracker.autorun((eventsType) => {
LocalEvents.remove({});
});

javascript array as values in associated array

I am trying to build an associated array dynamically like this.
How do I build it? With the following expected output?
"happy": [1,2,3,4,5],
"angry": [6,7,8,9,10]
$(document).ready(function() {
var videos = [];
$('.header-video__media').each(function(i, elem) {
var mediaElement = $(elem);
var mood = mediaElement.attr('data-mood');
headerVideo = new HeaderVideo({
index:i,
element: '.header-video',
media: '.header-video__media',
playTrigger: '.header-video__play-trigger',
closeTrigger: '.header-video__close-trigger',
nextTrigger: '.header-video__next-trigger'
});
videos.mood = mood;
videos.push (headerVideo);
});
In the JavaScript world associative array are represented by literal objects:
// declaration of a new literal object
var videos = {};
// test if the key is already setted or not
if(!videos.hasOwnProperty(mood)){
// if not, initiate a new array
videos[mood] = [headerVideo];
}else{
// if yes, add add the value to the existing array
videos[mood].push(headerVideo);
}

Looping through deeply nested properties - React

I'm trying to .map through data returned from an API (the NASA API). The issue I'm having is with deeply nested properties -- here's an example.
What's the best way to get the nested name and estimated_diameter properties data in React? All the data's being brought in just fine via axios. Logging out the state returns this:
I'm having trouble map'ing through the data because of the nested objects and arrays.
Assume the nasa data json is saved in the variable nasaData, the code below will print all the name and the estimated_diameter
var nearEarthObjects = nasaData['near_earth_objects'];
for (var property in nearEarthObjects) {
if (nearEarthObjects.hasOwnProperty(property)) {
var data = nearEarthObjects[property];
data.forEach(function(d){
console.log(d['name']);
console.log(d['estimated_diameter']);
});
}
}
ps: this might be for a reactjs project but it's really just javascript
You can map through the dates first.
const { near_earth_objects } = nasaData; //assuming nasaData is the json object
const dateKeys = Object.keys(near_earth_objects);
const nameAndEstimatedDiameters = dateKeys.map((dateKey) => {
const dateData = near_earth_objects[dateKey];
const { name, estimated_diameter } = dateData;
return { name, estimated_diameter };
});
//now nameAndEstimatedDiameters is an array of objects here
//which you can map again

Categories