简体   繁体   English

无法动态分配 JS object 属性

[英]Can't dynamically assign JS object property

I'm trying to make a web app that takes in the names of several people and assigns each one a friend but am running into an issue assigning the friends.我正在尝试制作一个 web 应用程序,该应用程序接受几个人的名字并为每个人分配一个朋友,但在分配朋友时遇到了问题。

The issue I'm running into is that it properly assigns the first few people friends, but always crashes on the second last person in the array and displays the error message我遇到的问题是它正确地分配了前几个人的朋友,但总是在数组中倒数第二个人崩溃并显示错误消息

TypeError: Cannot set property 'friend' of undefined. TypeError:无法设置未定义的属性“朋友”。

Here is a snippet from my app.js code.这是我的app.js代码中的一个片段。

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({extended: true}));

let participantsObject = {};
let participantsArray = [];
let randomNumber;

app.get("/new", function(req, res) {
  res.sendFile(__dirname + "/new.html");
});

app.post("/new", function(req, res) {
  participantsObject[req.body.person] = {};
  participantsArray.push(req.body.person);
  res.redirect("/new");
});

app.get("/setup", function() {
  let size = participantsArray.length;
  let participantsWithoutAGifter = participantsArray;

  for (var i = 0; i < size; i++) {
    randomNumber = Math.floor(Math.random() * participantsWithoutAGifter.length)
    participantsObject[participantsArray[i]]["friend"] = participantsWithoutAGifter[randomNumber];
    participantsWithoutAGifter.splice(randomNumber, 1);
  }

  console.log(participantsObject);

});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

And here is my new.html这是我的new.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form method="post">
      <input type="text" name="person" placeholder="Enter participant name" autofocus>
      <button type="submit">Add</button>
      <button type="button"><a href="/setup">Finished</a></button>
    </form>
  </body>
</html>

Ideally, it would be able to assign all participants a friend and then log the entire object.理想情况下,它将能够为所有参与者分配一个朋友,然后记录整个 object。

Any help would be much appreciated, thanks in advance.任何帮助将不胜感激,在此先感谢。

The property the loop is trying to select does not yet exist on the participantsObject .循环试图 select 的属性在participantsObject对象上尚不存在。

Add a check if the property is there.添加检查该属性是否存在。 If it is, then assign the friend property on the object.如果是,则在 object 上分配friend属性。 And if not, then assign a new object with a friend property.如果没有,则分配一个带有friend属性的新 object。

for (var i = 0; i < size; i++) {
  randomNumber = Math.floor(Math.random() * participantsWithoutAGifter.length);
  let participantsIndex = participantsArray[i];
  if (participantsObject.hasOwnProperty(participantsIndex)) {
    participantsObject[participantsIndex]['friend'] = participantsWithoutAGifter[randomNumber]
  } else {
    participantsObject[participantsIndex] = {
      friend: participantsWithoutAGifter[randomNumber]
    }
  }
  participantsWithoutAGifter.splice(randomNumber, 1);
}
// participantsObject[participantsArray[i]]["friend"] = participantsWithoutAGifter[randomNumber]; // <-- this will not work

const newProperty = 'friend'
participantsObject[participantsArray[i]] = {
  ...participantsObject[participantsArray[i]],  // <-- so that you don't lose other perperties
  [newProperty]: participantsWithoutAGifter[randomNumber]
}

Alternately you can use Object.assign或者,您可以使用 Object.assign

const newProperty = 'friend'
const source = {}
source[newProperty] = participantsWithoutAGifter[randomNumber]
Object.assign(participantsObject[participantsArray[i]], source )

Here is link to code: https://github.com/ApolloTang/stackoverflow-soln--cannot-dyn-assign-js-obj-props/blob/main/app.js这是代码的链接: https://github.com/ApolloTang/stackoverflow-soln--cannot-dyn-assign-js-obj-props/blob/main/app.js

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

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