简体   繁体   English

如何动态创建 object 属性并使用 for 循环分配值

[英]How to dynamically create an object property & assign values using a for loop

Please can someone educate me on how to assign values to object properties correctly in the given scenario:请有人教我如何在给定的场景中正确地为 object 属性赋值:

I am taking the value of a text area, splitting the value at a new line.我正在获取文本区域的值,将值拆分为新行。 I need to assign these split values to a property of an object in an array.我需要将这些拆分值分配给数组中 object 的属性。 See below code:见下面的代码:

var items = [{}];

function process() {
    var i = 0;
    items.forEach((j) => {
        j.self = document.getElementById('input').value.split('\n');
    });

process() is called when a button is clicked.当单击按钮时调用 process()。

In the console, I get the following:在控制台中,我得到以下信息:

在此处输入图像描述

Instead of key[0] for example having 10 self values as an array, I need a single value to be assigned to key[0] as the value of the self property.我需要将单个值分配给 key[0] 作为 self 属性的值,而不是 key[0] 例如将 10 个 self 值作为数组。 The second split needs to be assigned to key 1 .self for example.例如,第二个拆分需要分配给键1 .self。

Expected output would be like this (apologies if not totally accurate):预期的 output 会是这样的(如果不完全准确,请道歉):

items[0]{self: split-string[0]},
items[1]{self: split-string[1]},
items[2]{self: split-string[2]},

And so forth...等等……

Rather than (what is shown in the console):而不是(控制台中显示的内容):

items[0].self[0] = split-string[0];
items[0].self[1] = split-string[1];
items[0].self[2] = split-string[2];

If that makes sense, please can someone assist.如果这是有道理的,请有人帮忙。

It is unclear exactly what you're trying to get out, but if I understand correctly its an array of objects with a property self containing a line from the input.目前还不清楚你到底想得到什么,但如果我理解正确的话,它是一个对象数组,它的属性self包含输入中的一行。

If that assumption is correct, this should work:如果这个假设是正确的,这应该有效:

 document.getElementById("clickme").addEventListener("click",process); function process(){ const items = document.getElementById("input").value.split("\n").map(line => ({self:line})); console.log(items); }
 <textarea id="input" rows="5">Line1 Line2 Line3 Line4</textarea> <button id="clickme">Process</button>

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

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