简体   繁体   中英

push Object in array in $.each

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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