Home > OS >  Javascript check if object is in another object and match length to other objects keys
Javascript check if object is in another object and match length to other objects keys

Time:03-23

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.

CodePudding user response:

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
}
}
*/

CodePudding user response:

Perhaps you could use some form of iteration with coalescing operator (||)...

someObjArray.forEach(function(x) {
    return {
        // if the obj does not have key/value pair for that date, it will use 0 (the value to the right of ||)
        2021-12-23: (x['2021-12-23'] || 0),
        2021-12-24: (x['2021-12-24'] || 0),
        2021-12-27: (x['2021-12-27'] || 0),
        2022-01-05: (x['2021-01-05'] || 0)
    }
 });

CodePudding user response:

Here's an implementation using Object.entries and Array.prototype.reduce but there are actually a lot of way to approach this.

const original = {
  "2021-12-23": 4,
  "2021-12-24": 7,
  "2021-12-27": 6,
  "2022-01-05": 5
}
function filterObjectByKey( o, key ){
  return Object.entries(o).reduce((acc, [k,v])=>{
    acc[k] = ( k === key ) ? v : 0;
    return acc;
  }, {});
}
const filtered = filterObjectByKey( original, "2022-01-05");

console.log( filtered );

Updated: The function can also accept the secondary object as an argument and filter based on its keys:

const original = {
  "2021-12-23": 4,
  "2021-12-24": 7,
  "2021-12-27": 6,
  "2022-01-05": 5
}
const secondary = {
  "2022-01-05": 5
}
function filterObjectByKey( o, sec ){
  const keys = Object.keys(sec);
  return Object.entries(o).reduce((acc, [k,v])=>{
    acc[k] = keys.includes(k) ? v : 0;
    return acc;
  }, {});
}
const filtered = filterObjectByKey( original, secondary );

console.log( filtered );

  • Related