0

Please can someone educate me on how to assign values to object properties correctly in the given scenario:

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. 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.

In the console, I get the following:

enter image description here

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. The second split needs to be assigned to key1.self for example.

Expected output would be like this (apologies if not totally accurate):

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.

6
  • 3
    You're overwriting j with j++? --- Edit: Why are you using a number and then attaching a property to it? Commented May 7, 2021 at 13:44
  • Really struggling to see what you're trying to get from the split strings. Can you show your expected output Commented May 7, 2021 at 13:50
  • @evolutionxbox I removed the j declaration and the j++, still the same output Commented May 7, 2021 at 13:54
  • Please update the question to show us what's changed? Commented May 7, 2021 at 13:54
  • 1
    @srcomptn Yep makes sense - exactly what my answer produces Commented May 7, 2021 at 14:07

1 Answer 1

1

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.

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Very sorry for my god awful explanation, but this is exactly what I meant. Thank you very much for this
@srcomptn ha... no probs I sort of got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.