-2

How to save javascript data from a loop to an array?

for (i = 0; i < jsonData.Data.Positions.length; i++) {
     var h = jsonData.Data.Positions[i].Oid;
}
  • `var data = jsonData.Data.Positions.map(p => p.Oid);` –  Feb 14 '19 at 09:40
  • You want to push your current element to an array? So `yourArray.push(h);`? – CodeF0x Feb 14 '19 at 09:40
  • 3
    Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) and [Returning only certain properties from an array of objects in Javascript](https://stackoverflow.com/questions/24440403) and [Javascript Array of objects get single value](https://stackoverflow.com/questions/23036023) and [Construct an array of elements from an array of objects?](https://stackoverflow.com/questions/23005348) – adiga Feb 14 '19 at 09:42

6 Answers6

0

Insert the data in the array using push

var arr=[];
for (i = 0; i < jsonData.Data.Positions.length; i++) {
     var h = jsonData.Data.Positions[i].Oid;
     arr.push(h);
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0
var data = [];
for (i = 0; i < jsonData.Data.Positions.length; i++) {
     var h = jsonData.Data.Positions[i].Oid;
     data.push(h)
}

//OR
var data = jsonData.Data.Positions.map(item => item.Oid);
Code Spirit
  • 3,992
  • 4
  • 23
  • 34
0

Your variable jsonData.Data.Positions is probably already an array.

0

Use .push() method to add values to array.

var h=[];
for (i = 0; i < jsonData.Data.Positions.length; i++) {
     h.push(jsonData.Data.Positions[i].Oid);
}
console.log(h);
Selvam M
  • 520
  • 4
  • 18
0

You can do it within a loop:

var array = []
for (i = 0; i < jsonData.Data.Positions.length; i++) {
     array.push(jsonData.Data.Positions[i].Oid);
}

Or in a more functional-way:

var array = jsonData.Data.Positions.map(p => p.Oid)
0xc14m1z
  • 3,675
  • 1
  • 14
  • 23
0

map instead of for loop

var h = jsonData.Data.Positions.map(function (x) { return x.0id });