0

Maybe I'm just blind, but I'm struggling for a good amount of time now:

I have a small piece of JS-Code here:

var linkInput = $('#Link input.gwt-TextBox').val();
var parentRow = $('#Link').parent().parent();
var links = linkInput.split("|");

// hide text-input
$(parentRow).hide();

// get rid of empty elements
links = links.filter(Boolean);

var aSites = [];
var oSite = {};

$(links).each(function (k, v) {

    splits = v.split(".");
    domainName = splits[1];
    oSite.name = domainName;
    oSite.url = v;
    aSites.push(oSite);
});

console.log(aSites);

To specify: Get the value of an input-field, hide the row afterwards and save all the values in an object, which is then pushed into an array.

The parameter, taken from the console-tab of google Chrome:

var links = ["www.myshop1.de/article/1021581", "https://www.myshop2.de/article/1021581"] [type: object]

I thought, I iterate through all elements of this object (in that case 2 times), push the values into an object and the object into an array, to have access to all of them afterwards.

At some point however, I seem to override my former values, since my output looks like this:

0: {name: "myshop1", url: "https://www.myshop1.de/1021581"}
1: {name: "myshop2", url: "https://www.myshop2.de/1021581"}
length: 2
__proto__: Array(0)

Where is my mistake here? Is there a smarter way to realize this?

On a sidenote:

I tried to use only an array (without adding an object), but it seems like I can't use an associative key like this:

var myKey = "foo";
var myValue = "bar";
myArray[myKey] = myValue

1 Answer 1

3

You should move this:

var oSite = {};

...inside the each callback below it, because you need a new object in each iteration.

Otherwise you are mutating the same object again and again, pushing the same object repeatedly to the aSites array, which ends up with multiple references to the same object.

Not related, but you can use $.map to create your array (or vanilla JS links.map()):

var aSites = $.map(links, function(v) {
    return { name: v.split(".")[1], url: v };
});
Sign up to request clarification or add additional context in comments.

2 Comments

sigh .. I knew it would be something trivial. Thank you! That did it. I'll accept this answer as soon as I can.
or use asites.push({ name: ..., url: ... });

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.