Smac
Smac

Reputation: 401

How to convert id's in array of objects to a list JavaScript

I am trying to get all IDs from an array objects and put the in a list so they can be passed to a method (API)

    var tempObj= Getlist();
    var tmpList = tempObj.listOfdata.filter(function (result) { return (result.Id) });

    var data = tmpList

then I have my AJAX call

$.ajax({
        url: url,
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        async: true,
        method: 'POST',
        success: function (data) {
            console.log(data);       
        }
    });

no data is being passed

Upvotes: 1

Views: 8864

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

If you want to extract values from a collection of objects, don't use filter. Use map.

let list = [
  { id: 1 },
  { id: 3 },
  { id: 23 },
  { id: 16 }
];

let data = list.map((obj) => obj.id);
console.log(data);

In ES5:

var list = [
  { id: 1 },
  { id: 3 },
  { id: 23 },
  { id: 16 }
];

var data = list.map(function(obj) {
  return obj.id;
});
console.log(data);

Upvotes: 5

Related Questions