简体   繁体   中英

Javascript: Add array elements to another array

I need to split elements in array noted below into 2 separate arrays:
data and labels:

Example using below would look like this:

data: [9, 23, 1, 6]
labels: ['service-1', 'service-2', 'service-3', 'service-4']

    Array[16]
       .    0: Object
           .    data: 9
           .    labels: "service-1"
           .    __proto__: Object
       .    1: Object
           .    data: 23
           .    labels: "service-2"
           .    __proto__: Object
       .    2: Object
           .    data: 1
           .    labels: "service-3"
           .    __proto__: Object
       .    3: Object
           .    data: 6
           .    labels: "service-4"
           .    __proto__: Object

I'm trying to keep this simple as possible as I've tried several different things that have not worked including reference in this post: add array elements to other ,

Try this:

var dataLabels = [
  {data: 9, label: "service-1"},
  {data: 23, label: "service-2"},
  {data: 1, label: "service-3"},
  {data: 6, label: "service-4"}
];

var data = [];
var labels = [];

dataLabels.forEach(function(element) {
    data.push(element.data);
    labels.push(element.label);
});

Assuming your array has a JS object notation, I think this should work:

var data = [];
var labels = [];

for (var i= 0;i<16; i++){
    data[i] = array[i].data;
    labels[i] = array[i].labels;
}

This should do the trick. Although perhaps a loop will suffice.

var dataLabels = [
  {
    data: 9,
    labels: "service-1"
  }, {
    data: 23,
    labels: "service-2"
  }
];

var data = dataLabels.map(function(element) {
  return element.data;
});

var labels = dataLabels.map(function(element) {
  return element.labels;
});

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