0

Let's say I have a JavaScript object that is made up of several key/value pairs of string keys and JavaScript objects.

var obList = { key:{..}, key2:{..}, key3:{..}, ... }

And I construct a new set, obList2

var obList2 = { key:{..}, key2:{..}, key3:{..}, ... }

I want to write a function that modifies obList based on obList2. The initial step I'm having trouble with is removing all objects in obList that have a key not present in obList2. Any thoughts/implementation of this would be v helpful. Thank you!

0

2 Answers 2

1

You can loop over objects using a for .. in loop and check if properties exist using Object.hasOwnProperty().

Example:

for (var prop in obList) {
    if (obList.hasOwnProperty(prop) && !obList2.hasOwnProperty(prop)) {
        delete obList[prop];
    }
}

The first condition is a safeguard against modifications to Object.prototype and the second checks to see if the property isn't present on the second object.

Sign up to request clarification or add additional context in comments.

Comments

0

Basic element for your code: ability to check if a particular key is missing from an object. Here's how you'd do it:

if (window.bla === undefined) { 
  console.log("Key bla is missing!")
}

2 Comments

What if a property is specifically set to undefined?
Great point. Don't know if it's practically applicable, but I did learn something today - I won't be comparing stuff to undefined anymore :-). Thanks, Radu!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.