2

If I have a JavaScript object:

var object = {
  propertyOne: undefined,
  propertyTwo: 'defined',
  propertyThree: 'defined',
  propertyFour: undefined
}

How can I create a method that will list the properties with undefined values (in the example's case, propertyOne and propertyFour).

I'm quite new to JavaScript, and this is what I had so far:

function getEmptyProperties(object) {
  var emptyProps = [];
  for (var property in object) {
    if (object.property === undefined) {
      emptyProps += property
    }
  }
  return emptyProps
}

But this returns ALL of the properties, regardless if they are undefined or not.

I know I'm missing some things that are principal in JS, but can't figure it out. Kindly help please?

0

3 Answers 3

3

Iterate over the object with:

Object.keys(object).forEach(function(val, i){
  if (object[val] === undefined){
  //do things to save the properties you want to save or delete
  }
})

For fundamentals I might suggest Eloquent JavaScript. It's free. You have a number of syntax errors in your code that could be fixed if you read the first 6ish chapters.

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

Comments

0
var getEmptyProperties = function(object) {
  var emptyProps = [];
  for (var property in object) {
    if (object[property] === undefined) {
      emptyProps.push(property);
    }
  }
  return emptyProps
}

1 Comment

You should explain what this code does and how, so it's easier to understand.
0

You may use filter, to get an array of only the properties that are undefined:

var obj = {
    propertyOne: undefined,
    propertyTwo: 'defined',
    propertyThree: 'defined',
    propertyFour: undefined
};

var undefProps = Object.keys(obj).filter(function (key) {
    return obj[key] === undefined;
});

// undefProps: ["propertyOne", "propertyFour"]

And with an arrow function!:

var undefProps = Object.keys(obj).filter(k => obj[k] === undefined);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.