javascript - 在 for 循环中向对象添加键值对
问题描述
我很难让我的 for 循环向对象添加新的键值对。更改已经存在的键的当前值没有问题,但由于某种原因,它不会添加新的
async function test(messagesWithSomeContent) {
for (i = 0; i < messagesWithSomeContent.length; i++) {
messagesWithSomeContent[i]["photo"] = 'please add this'; // this does not add a new key value pair
messagesWithSomeContent[i]["sender"] = 'change this'; // this works
console.log(messagesWithSomeContent[i]);
}
return win(await Promise.all(messagesWithSomeContent));
}
async function win(yay) {
console.log('yay');
}
messageWithSomeContent
[ { _id: 5e8f5a6a2582bf629998c3fe,
sender: '5e8f8d6be541b07ab8d8770b',
content: { content: 'Welcome to' },
__v: 0 },
{ _id: 5e8f594768fdda61d4f2ef6d,
sender: '5e8f86852c2a5174f3ca5e8c',
content: { content: 'hello test' },
__v: 0 },
{ _id: 5e8f585ee3eaa06136048b5c,
sender: '5e8f883627154676347fe286',
content: { lol: 'yeesh' },
__v: 0 } ]
我看了一些类似的帖子,他们的解决方案不起作用。
解决方案
Promise.all
必须收到一系列承诺。这样做的一种方法是使用map
参数数组,在回调中调用函数。
Promise.all(parameters.map(parameter => myAsyncFunction(parameter)));
var messages = [
{_id: '5e8f5a6a2582bf629998c3fe', sender: '5e8f8d6be541b07ab8d8770b', content: { content: 'Welcome to' }, __v: 0},
{_id: '5e8f594768fdda61d4f2ef6d', sender: '5e8f86852c2a5174f3ca5e8c', content: { content: 'hello test' }, __v: 0},
{ _id: '5e8f585ee3eaa06136048b5c', sender: '5e8f883627154676347fe286', content: { lol: 'yeesh' }, __v: 0}];
async function test() {
for (var i = 0; i < messages.length; i++) {
messages[i]["photo"] = 'please add this';
messages[i]["sender"] = 'change this';
}
var result = await Promise.all(messages.map(el => win(el)));
console.log(result); // Should contain an array with all responses
}
async function win(param) {
console.log(param);
return param.photo;
}
test();
推荐阅读
- python - 使用 OpenCV 时,Cython 比 Python 慢
- wordpress - 如何仅将 div 添加到深度 2 子菜单?
- python-3.x - Python循环和列表追加交互
- php - 如何在php中访问foreach循环变量?
- symfony - Symfony CLI 服务器使用 mkcert 证书
- php - Easyadmin 3 - 如何呈现嵌入式表单?
- python - 将参数添加到 URL 以在 Python 中进行迭代
- node.js - Mongoose 按其他集合的字段排序
- sql - 如何迭代具有已知起始位置和混合列排序的行,就像遍历相应的索引一样?
- asp.net-core - SignalR 中基于资源的授权