0

I need help doing the following. I need to duplicate an array, update a value and insert it into a new object.

My Code right now:

// Sample test values {name:'The initial value', altName:'a first Name;a second name'}

var allAltName = test.altName;//Test come from a forEach() Iteration

        if (test.altName) {//First I check if ther is my parama altName
            var b,
                countAllAltName = allAltName.split(';'); //Here I split my parameter string based on ';'

            if (countAllAltName.length > 0) {
                for (b = 0; b < countAllAltName.length; b = b + 1) {
                    var originalName = {};//I create a new object
                    originalName = test;//I load my existing object into a blank object

                    if (!ret["Index"]) // I check if my final object Key exist
                        ret["Index"] = {}; // if not create new object
                    if (!ret["Index"]["Index"]) // check another key
                        ret["Index"]["Index"] = []; // if not create new
                    originalName.name = countAllAltName[b];//Update my new object originalName with new value

                    ret["Index"]["Index"].push(originalName); // push current element in the designated list

                    ret["Index"]["Index"].sort(function (a, b) {
                        return a.name.localeCompare(b.name);
                    });
                    console.log(ret);
                }
            }
        }

Issue is ret contains the required Object keys,but all value of name in each aray have the same last value of altName I console.log() at each step what is the value of originalNameit always looks good. Why the end results failed, and where I'm overwriting my data.

1
  • please add some raw data and the wanted result. Commented Aug 29, 2017 at 9:19

1 Answer 1

1

When you write originalName = test, you tell to JS that originalName is an "alias" for test (both share the same reference).

The behaviour is what you change in originaleName, it's impacted in test and vice versa (behaviour true only for Array and Object).

If you want to do a real copy, the simplest way (but with restrictions) is :

originalName = JSON.parse(JSON.stringify(test));

Last things : var originalName = {} is not an Array but an Object. There are some important differences between them

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

1 Comment

Thanks @fefux I corrected my mistake on denomination for Array and Object. Your answer works great and I learn something new about the alias. I thought initially the equal sign created the copy as I'm used to doing when assigning a value to a variable.

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.