简体   繁体   English

Javascript如何为未定义的对象键赋值?

[英]Javascript how to assign value to undefined object key?

I would like to programatically assign values to 'not yet' initialized key in object, like below:我想以编程方式为对象中的“尚未”初始化键赋值,如下所示:

const a = {};
// year, month, date is a variable
a[year][month][date] = some data; 

I know above wouldn't work unless I assign year and month before assigning to date key,我知道除非我在分配日期键之前分配yearmonth ,否则上述方法不起作用,

but I am assigning this programatically so I can't do something like但我以编程方式分配这个,所以我不能做类似的事情

a:{
  2020:{
    10:{
      3: some data
    }
  }
}

manually like this.像这样手动。

What would be the best way to assign value to undefined key?为未定义的键赋值的最佳方法是什么?

There is no simple way to do that.没有简单的方法可以做到这一点。

You would need to so something like:你需要像这样:

a[year] = {}
a[year][month] = {}
a[year][month][date] = 'some data';

You could use some function like this:你可以使用这样的函数:

function setByPath(obj, path, value) {
    var parts = path.split('.');
    var o = obj;
    if (parts.length > 1) {
      for (var i = 0; i < parts.length - 1; i++) {
          if (!o[parts[i]])
              o[parts[i]] = {};
          o = o[parts[i]];
      }
    }

    o[parts[parts.length - 1]] = value;
}

Usage:用法:

setByPath(a, 'year.month.date', 'some data');

Please note that this function is only as an example, and it can cause problems in certain cases.请注意,此功能仅作为示例,在某些情况下可能会导致问题。 It is to show the idea.它是为了展示这个想法。

You could iterate the keys without the last one for assigning the value.您可以在没有最后一个键的情况下迭代键来分配值。

 const assign = (object, [...keys], value) => { const last = keys.pop(); keys.reduce((o, k) => o[k] ??= {}, object)[last] = value }, a = {}; assign(a, [2020, 10, 3], 42); console.log(a);

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

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