0

I'm having a hard time searching/explaining what I'm trying to do, but I want to add data to a JavaScript object. The index that I want to add the data to may or may not exist, and that index name will be dynamic, so I can't just define all the objects at the start.

Lets say I'm adding to an object when users click links on my site. I've defined my object:

exampleObject = {};

If a user clicks a fruit link, I want to add the fruit to the object. I would normally do this:

exampleObject.fruit = {};
exampleObject.fruit.strawberry = true;

My issue is that I don't want to overwrite the object when the user clicks the next fruit. I would need to check if the object is defined and then add to it:

if ( typeof exampleObject.fruit === 'undefined' ){
    exampleObject.fruit = {};
    exampleObject.fruit.cherry = true;
} else {
    exampleObject.fruit.cherry = true;
}

What I'm wondering is if there is a shorthand way of doing the conditional above? I was hoping for a one-liner since I'll be doing this a lot. My next thought was to make a function for this, but I don't want to have to reinvent the wheel or restrict myself (like, if I want to use an array within this object to push all fruits into one index). jQuery is an option in this case, but not necessarily my first choice.

3 Answers 3

2
exampleObject = exampleObject || {};
exampleObject.fruit = exampleObject.fruit || {};
exampleObject.fruit.cherry = true;
Sign up to request clarification or add additional context in comments.

Comments

1

Based on the fact that you have said the index name will be dynamic, use square brackets to adjust the object key/index:

function addFruit (name) {

  exampleObject = exampleObject || {};
  exampleObject.fruit = exampleObject.fruit || {};

  if (typeof exampleObject.fruit[name] == 'undefined')
    exampleObject.fruit[name] = true;

}

1 Comment

This is along the lines of what I was thinking about doing with the function- appreciate the answer. I got it working using your response as my starting point (with a dynamic index like Brad suggested). Thanks.
1

I would go the function route, depending on how extreme your new indexes are. This will allow you to assign category and item in one go.

function checkOrAddKey(key, newItem) {
  if(!exampleObject.hasOwnProperty(key)) {
    exampleObject[key] = {};
    exampleObject[key][newItem] = true;
  }
  else {
    exampleObject[key][newItem] = true;
  }
}

checkOrAddKey('fruit', 'apple');
checkOrAddKey('fruit', 'banana');
checkOrAddKey('scone', 'cinnamon');

//exampleObject: { fruit: { apple: true, banana: true }, scone: { cinnamon: true } }

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.