gpt4 book ai didi

javascript - 在 JavaScript 中将数据动态写入嵌套对象

转载 作者:行者123 更新时间:2023-12-04 07:58:56 25 4
gpt4 key购买 nike

我想将数据(以对象的形式)作为值动态写入嵌套在另一个对象中的对象;并且还动态创建键的名称(在循环内)。
我当前的代码如下所示:

data = {'x': 2, 'y': 3}

master_obj = {'useless': {}, 'important': {}}

var block_ind = 0
let trials = 12
let trials_per_block = 4
for (trial_ind=0; trial_ind<trials; trial_ind++) {
// every 4 trials are in a new block
block_ind = trial_ind % trials_per_block == 0 ? trial_ind/trials_per_block : block_ind

master_obj['important']['block_0'+block_ind] = {}
master_obj['important']['block_0'+block_ind]['trial_0'+trial_ind] = data
}
console.log(master_obj)

代码的输出看起来像这样(也运行上面的代码片段):
Output of above snippet
而预期的输出是 [一个区块内的多次试验,而不是一次]:
useless: {}
important:
block_00:
trial_00: {x: 2, y:3}
trial_01: {x: 2, y:3}
trial_02: {x: 2, y:3}
trial_03: {x: 2, y:3}
block_01:
trial_04: {x: 2, y:3}
trial_05: {x: 2, y:3}
trial_06: {x: 2, y:3}
trial_07: {x: 2, y:3}
block_02:
trial_08: {x: 2, y:3}
trial_09: {x: 2, y:3}
trial_10: {x: 2, y:3}
trial_11: {x: 2, y:3}
任何和所有的帮助和建议表示赞赏!

最佳答案

问题是你没有复制 data ,你只是重复使用同一个对象。另一个问题是,当您尝试将另一个实例添加到现有块时,您正在覆盖之前创建的对象。
如何复制它是一个潜在的复杂主题(请参阅 this question's answers),但对于其自身的可枚举属性的浅拷贝,您可以使用扩展符号或 Object.assign使用对象字面量,参见 ***下面一行:

const data = {"x": 2, "y": 3}

const master_obj = {"useless": {}, "important": {}}

var block_ind = 0
let trials = 12
let trials_per_block = 4
const important = master_obj.important; // *** No need to repeat this
for (let trial_ind=0; trial_ind<trials; trial_ind++) {
// ^^^−−−− *** Declare your variables
// every 4 trials are in a new block
block_ind = trial_ind % trials_per_block == 0 ? trial_ind/trials_per_block : block_ind

// *** Only create this if it doesn't exist
if (!important["block_0"+block_ind]) {
important["block_0"+block_ind] = {}
}
important["block_0"+block_ind]["trial_0"+trial_ind] = {...data} // ***
}
console.log(master_obj)

另请注意,我添加了 constdatamaster_obj .无 let , const , 或 var ,你的代码成为我所说的 The Horror of Implicit Globals 的牺牲品.一定要声明你的变量。 (我建议总是使用 constlet ,永远不要使用 var 。)

对于它的值(value),您可以使用 Math.floor(trial_ind / trials_per_block)确定块号。这是加上几个模板文字和其他具有描述性名称的常量:

const data = {"x": 2, "y": 3};

const master_obj = {"useless": {}, "important": {}};

const trials = 12;
const trials_per_block = 4;
const important = master_obj.important;
for (let trial_ind = 0; trial_ind < trials; ++trial_ind) {
// Every 4 trials are in a new block
const blockKey = `block_0${Math.floor(trial_ind / trials_per_block)}`;

const trialKey = `trial_0${trial_ind}`;

if (!important[blockKey]) {
important[blockKey] = {};
}
important[blockKey][trialKey] = {...data};
}
console.log(master_obj);

关于javascript - 在 JavaScript 中将数据动态写入嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66564488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com