1

I have an array of objects like below, let's say arrayValues:

{ field1 : "933", field2 : "something", fieldN: "344" }
{ field1 : "21", field2 : "something", fieldN: "344" }
{ field1 : "34", field2 : "something", fieldN: "344" }

Using jQuery foreach I am trying to get value of field1 for each object in the array and then add them to another array, let's say newArray:

var newArray = [];
$.each(arrayValues, function () {   
   newArray.push('what to put here?');
});

At the end, newArray should contain: 933, 21, 34

How to do this?

Ha. Huynh
  • 1,772
  • 11
  • 27
Willy
  • 9,848
  • 22
  • 141
  • 284

2 Answers2

5

You don't need jQuery for this. jQuery is a framework primarily for amending the DOM. For working with arrays you just need plain old Javascript. As such, simply using map() will build the array you require:

let arrayValues = [
  { field1 : "933", field2 : "something", fieldN: "344" },
  { field1 : "21", field2 : "something", fieldN: "344" },
  { field1 : "34", field2 : "something", fieldN: "344" }
]

let newArray = arrayValues.map(o => o.field1);
console.log(newArray);

Note that if you would prefer to have the values as integers use o => parseInt(o.field1, 10)

If, for whatever reason, you did want to do this in jQuery then you would use $.map():

let newArray = $.map(arrayValues, o => o.field1);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Consider the following code.

$(function() {
  var arr = [{
      field1: "933",
      field2: "something",
      fieldN: "344"
    },
    {
      field1: "21",
      field2: "something",
      fieldN: "344"
    },
    {
      field1: "34",
      field2: "something",
      fieldN: "344"
    }
  ]

  var newArr = [];

  $.each(arr, function(k, v) {
    newArr.push(parseInt(v.field1, 10));
  });
  console.log(newArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Please review: https://api.jquery.com/jquery.each/

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

Twisty
  • 30,304
  • 2
  • 26
  • 45