How do i filter JSON based on a key, so i only have a list of one type of key for all objects

Viewed 460

[
  {
    "id":100,
    "account_id":8,
    "name":"Out of Service",
    "default":false,
    "created_at":"2012-02-06T08:51:29.720-06:00",
    "updated_at":"2012-02-06T08:51:29.720-06:00"
  },
  ...
]

This is my sample object. I get this from an url fetch app request. How can i filter this so i can publish a list of only one type of Value.

For example : if I want to filter it for Key Id, i want to get a list that is something like : 100,101,... So on.

Thanks

4 Answers

Instead of Array.prototype.filter() you should use Array.prototype.map()

Code:

const data = [
  {
    "id":100,
    "account_id":8,
    "name":"Out of Service",
    "default":false,
    "created_at":"2012-02-06T08:51:29.720-06:00",
    "updated_at":"2012-02-06T08:51:29.720-06:00"
  },
  {
    "id":101,
    "account_id":8,
    "name":"Out of Service",
    "default":false,
    "created_at":"2012-02-06T08:51:29.720-06:00",
    "updated_at":"2012-02-06T08:51:29.720-06:00"
  },
]

const result = data.map(obj => obj.id)

console.log(result)

For arrow functions (=>) won't work.

Use:

function testIt()
{
  var sample = [
    {
      "id":100,
      "account_id":8,
      "name":"Out of Service",
      "default":false,
      "created_at":"2012-02-06T08:51:29.720-06:00",
      "updated_at":"2012-02-06T08:51:29.720-06:00"
    },
    {
      "id":101,
      "account_id":8,
      "name":"Out of Service",
      "default":false,
      "created_at":"2012-02-06T08:51:29.720-06:00",
      "updated_at":"2012-02-06T08:51:29.720-06:00"
    },
  ];  
    var result = sample.map(function(elt) { return elt.id; });
    Logger.log(result); //  [100.0, 101.0]

    }

You could alternatively use Array.reduce although I'm not sure there are any benefits over Yosvel's map method:

const data = [
  {
    "id":100,
    "account_id":8,
    "name":"Out of Service",
    "default":false,
    "created_at":"2012-02-06T08:51:29.720-06:00",
    "updated_at":"2012-02-06T08:51:29.720-06:00"
  },
  {
    "id":102,
    "account_id":8,
    "name":"Out of Service",
    "default":false,
    "created_at":"2012-02-06T08:51:29.720-06:00",
    "updated_at":"2012-02-06T08:51:29.720-06:00"
  },
  {
    "id":105,
    "account_id":8,
    "name":"Out of Service",
    "default":false,
    "created_at":"2012-02-06T08:51:29.720-06:00",
    "updated_at":"2012-02-06T08:51:29.720-06:00"
  },
]

const res = data.reduce(
  (acc, val) => {
    return [...acc, val.id]
  },
  []
)
console.log(res)

const extractFieldArray = (data, key) => data.map(d => d[key]);

//data is your object, key is what you want to extract, like an id

Related