Jim from Princeton
Jim from Princeton

Reputation: 741

Copy Javascript object array value

from a dropdown I'm selecting an array from a javascript object:

$("#selector").change(function() {
    let array = [];
    Object.values(group[$("#selector").val()]).forEach(x => array.push(x));
    console.log(`Group: ${$("#selector").val()}, Array: ${array}`);
});

against an array such as:

let group = {
LocationA: [
{
        name: "A",
        length: 11,
        width: 9,
        height: 9
    },
    {
        name: "B",
        length: 26,
        width: 6,
        height: 20
    },
    {
        name: "C",
        length: 16,
        width: 12,
        height: 14
    }
],
locationB: [{
        name: "S-10662",
        length: 32,
        width: 18,
        height: 12
    }...

But the array outputs as a list of [object Object], not an array. I'm having difficulty copying a value (which is an array) into an array. I've searched for such an example, I cannot find one here.

Upvotes: 1

Views: 60

Answers (2)

Pavlos Karalis
Pavlos Karalis

Reputation: 2976

I don't think you need the forEach because you're already extracting the values as an array with Object.values; you can directly store it to your array variable:

    let array = Object.values(group[$("#selector").val()]);

That gives you an array of objects; with the forEach you were telling javascript to iterate through each of those objects, which isn't possible. If the goal was to also extract the values of those objects, then you could do:

$("#selector").change(()  => {
    let array = Object.values(group[$("#selector").val()]);
    console.log(array)
    let expandedArray = [];
    array.forEach(object => {
        expandedArray = [...Object.values(object), ...expandedArray]
    });
    console.log(expandedArray)
});

Upvotes: 1

Avinash Dalvi
Avinash Dalvi

Reputation: 9321

Change this line to :

console.log(`Group: ${$("#selector").val()}  Array: `, samplearray);

Variable you can console like this for printing array can't concatenate.

let group = {
  LocationA: [{
      name: "A",
      length: 11,
      width: 9,
      height: 9
    },
    {
      name: "B",
      length: 26,
      width: 6,
      height: 20
    },
    {
      name: "C",
      length: 16,
      width: 12,
      height: 14
    }
  ],
  locationB: [{
    name: "S-10662",
    length: 32,
    width: 18,
    height: 12
  }]
};
$("#selector").change(function() {
  let samplearray = [];
  Object.values(group[$("#selector").val()]).forEach(x => samplearray.push(x));
  console.log(`Group: ${$("#selector").val()}  Array: `, samplearray);
  console.log(samplearray);
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<select id="selector">
<option value="locationB" >locationB</option>
<option value="LocationA" >LocationA</option>
</select>
</body>

Upvotes: 1

Related Questions