John Seen John Seen - 5 months ago 16
JSON Question

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

Answer

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;
});
console.log(op);