首页 > 解决方案 > 在 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 } ]

我看了一些类似的帖子,他们的解决方案不起作用。

标签: javascriptmongodb

解决方案


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();


推荐阅读