Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Добавить свойство в конец ассоциативного массива (https://javascript.ru/forum/misc/80855-dobavit-svojjstvo-v-konec-associativnogo-massiva.html)

Bromin 15.08.2020 16:51

Добавить свойство в конец ассоциативного массива
 
Помогите Пожалуйста
Есть код:

var channels = ['channel1', 'channel2', 'channel3', 'channel4'];
var commands = ["hello", "goodbye", "send", "countdown", "backcountdown"];
var cooldown = {};
for(i of commands) {
	cooldown[`${i}`] = {
		ready: true,
		cooldown: {}
	}
};
console.log(cooldown);


Он выводит:
{
	hello: { ready: true, cooldown: {} },
	goodbye: { ready: true, cooldown: {} },
	send: { ready: true, cooldown: {} },
	countdown: { ready: true, cooldown: {} },
	backcountdown: { ready: true, cooldown: {} }
}


Я хочу сделать так, чтобы в cooldown.(команды от hello до backcountdown).cooldown было
{
	'channel1': true,
	'channel2': true,
	'channel3': true,
	'channel4': true
}

То есть чтобы:
cooldown = {
	hello: { ready: true, cooldown: {'channel1': true, 'channel2': true, 'channel3': true, 'channel4': true} },
	goodbye: { ready: true, cooldown: {'channel1': true, 'channel2': true, 'channel3': true, 'channel4': true} },
	send: { ready: true, cooldown: {'channel1': true, 'channel2': true, 'channel3': true, 'channel4': true} },
	countdown: { ready: true, cooldown: {'channel1': true, 'channel2': true, 'channel3': true, 'channel4': true} },
	backcountdown: { ready: true, cooldown: {'channel1': true, 'channel2': true, 'channel3': true, 'channel4': true} }
}


Но я не должен каждый раз переписывать cooldown.(команды от hello до backcountdown).cooldown а коде, а он должен сам дописывать 'channeln': true столько сколько у меня каналов в массиве channels

laimas 15.08.2020 17:12

Ну так надо заполнять в цикле значение свойства cooldown значениями channels. Но это должен быть объект, а не массив, почему его сразу и не прописан должным образом. Делать это скриптом вроде бы и смысла не имеет в данном случае:

var channels = Object.fromEntries(['channel1', 'channel2', 'channel3', 'channel4'].map((e)=> [e, true]));

Bromin 15.08.2020 17:34

Большое Спасибо.
Я просто с JS начал самостоятельно учить и не знал этого.
И еще раз Большое Спасибо!

laimas 15.08.2020 18:07

Цитата:

Сообщение от Bromin
Я просто с JS начал самостоятельно учить и не знал этого.

Чего? Если как массив в объект преобразовать, то зачем? Почему ни сразу прописать так:

var channels = {channel1: true, channel2: true, channel3: true, channel4: true}, //уже готовый объект
    commands = ["hello", "goodbye", "send", "countdown", "backcountdown"],
    cooldown = {};
    
for(i of commands) {
    cooldown[i] = {
        ready: true,
        cooldown: channels //добавляем описанный объект свойству 
    }
}

console.log(cooldown)


И в данном случае `${i}` лишнее, кроме бесполезной нагрузки на парсер ничего не несет полезного.

рони 15.08.2020 18:13

Bromin,
<script>
var channels = ['channel1', 'channel2', 'channel3', 'channel4'];
var commands = ["hello", "goodbye", "send", "countdown", "backcountdown"];
var ready = true;
var f = a => [a, ready];
var com = channels.map(f);
var cooldown = Object.fromEntries(com);
cooldown = Object.fromEntries(commands.map(c => [c ,{ready, cooldown}]));
document.write(JSON.stringify(cooldown, "", 4));
  </script>

рони 15.08.2020 18:18

Цитата:

Сообщение от laimas
cooldown: channels //добавляем описанный объект свойству

лучше копию объекта
cooldown: {...channels}

laimas 15.08.2020 18:24

Цитата:

Сообщение от рони
лучше копию объекта

В общем да, вот почему он сразу не объект, зачем такие сложности.


Часовой пояс GMT +3, время: 03:17.