简体   繁体   中英

Javascript : Assigning one array to another array which is a property of an object

So I have this array

var collectData = ["one", "two"];

and an object

var datasets = {
   labels : ["something", "something"]
}

In my program collectData is dynamically generated and assigned values when the app is launched, I want to assign those values to the labels array inside the object. I tried following ways

labels : [].concat(collectData)
labels : collectData.slice()

but it didn't work. What am I doing wrong?

Just use call the concat on the array which you have initially. When you do [].concat you're just adding elements of collectData to a new array literal, so you end up with just collectData

var collectData = ["one", "two"];
var datasets = {
   labels : ["something", "something"].concat(collectData)
}

Also you can always do datasets.labels.concat(collectData) sometime later after declaring the object datasets

To modify a property, you use an assignment:

datasets.labels = collectData;

If you want to make a copy of the collectData array instead of assigning it directly, use:

datasets.labels = collectData.slice();

I do not fully understand what you're trying to do but I have two options for you:

  1. Add the array to the array of labels:

  var collectData = ["one", "two"]; var datasets = { labels : [] } datasets.labels.push(collectData); console.log(datasets.label); 

Result:

{
    labels: [["one","two"]]
}
  1. Adding the collectData values to the datasets.labels array (other option than the answer from Amit Joki)

  var collectData = ["one", "two"]; var datasets = { labels : [] } for(i=0; i<collectData.length; i++){ datasets.labels.push(collectData[i]); } console.log(datasets.labels) 

Result:

{
   datasets: ["one", "two"]
}

The problem was this, collectData was initialised in the global scope and assigned values inside a callback function. Then, when I tried to assign values to the labels array which is inside an object datasets and datasets itself is not inside the callback function but outside of it. For some reason I am not aware of all the data from the collectData array vanished once the program left the callback function making it completely blank again. And that is the reason why labels was still coming out as an empty array. I think I failed to properly explain the question. I thank everybody for taking their time out and answering. If someone can explain me the callback function quirk of resetting the array it would be great.

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