I apologize for the title. I’m not really sure how to best word this as I’m still learning Javascript.
I have an object of dates that have an occurence of dynamic values as follows: (Key = date, value = number)
2021-12-23: 4 2021-12-24: 7 2021-12-27: 6 2022-01-05: 5 ... etc
I also have another object that looks something like this:
2022-01-05: 5
Basically, I need the second object to populate 0 for all non-matching keys. For example, the second object would need to look as follows (where the value of the match does not matter):
2021-12-23: 0 2021-12-24: 0 202-12-27: 0 2022-01-05: 5
I’m really stumped on this one, any javascript help would be immensely appreciated.
Advertisement
Answer
OK so what you want to do in order to achieve this is loop through all the keys of the first object (the one with the several DateString keys/Number values) and set the new numeric value to be 0 if that key is not included in the second object.
From your description:
const firstObject = { 2021-12-23: 4, 2021-12-24: 7, 2021-12-27: 6, 2022-01-05: 5 } const secondObject = { 2022-01-05: 5 }
seems like the code here would benefit from Object.entries
which is a function that you can run on an object Object.entries(myObject || {})
and it will return a 2-d array of the Object’s [[key, val], [key, val]]
.
So your final code will look like:
const mapTo0s = (firstObject, secondObject) => { return Object.fromEntries(Object.entries(firstObject).map(([dateString, value]) => { if (!secondObject[dateString]) { return [dateString, 0]; } return [dateString, value]; // assumes you want to keep the value as is when the secondObject has the value. })) };
Object.fromEntries
is another javascript method which converts a 2-d array of arrays to an object with corresponding keys. So if you send in [['05-10-2021', 3]]
it will return {'05-10-2021': 3 }
.
You can run that function like this:
const result = mapTo0s(firstObject, secondObject) // should result in: console.log({ result }) /* { result: { 2021-12-23: 0, 2021-12-24: 0, 202-12-27: 0, 2022-01-05: 5 } } */