简体   繁体   English

动态添加到对象并创建(如果未定义)?

[英]Dynamically add to object and create if undefined?

I'm having a hard time searching/explaining what I'm trying to do, but I want to add data to a JavaScript object. 我很难搜索/解释我要做什么,但是我想向JavaScript对象添加数据。 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. 在这种情况下,jQuery是一个选项,但不一定是我的首选。

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

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;

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM