Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract one field from json to form an array

I have an json array like this, I want to extract only the productId's to an array.

{
  "products": [
    {
      "productId": "a01",
      "uuid": "124748ba-6fc4f"
    },
    {
      "productId": "b2",
      "uuid": "1249b9ba-64d"
    },
    {
      "productId": "c03",
      "uuid": "124c78da-64"
    },
    {
      "productId": "d04",
      "uuid": "124ee9da-6"
    }
  ]
}

How can I do this in Javascript. I am not that good in JS, kidnly help me out. Thanks

like image 942
John Seen Avatar asked Jun 26 '16 18:06

John Seen


1 Answers

Use Array#map

The map() method creates a new array with the results of calling a provided function on every element in this array.(arr.map(callback[, thisArg]))

var input = {
  "products": [{
    "productId": "a01",
    "uuid": "124748ba-6fc4f"
  }, {
    "productId": "b2",
    "uuid": "1249b9ba-64d"
  }, {
    "productId": "c03",
    "uuid": "124c78da-64"
  }, {
    "productId": "d04",
    "uuid": "124ee9da-6"
  }]
};
var op = input.products.map(function(item) {
  return item.productId;
});
//Using arrow function-
//var op = input.products.map(item => item.productId);
console.log(op);
like image 200
Rayon Avatar answered Sep 18 '22 14:09

Rayon