最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - extract one field from json to form an array - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Jun 26, 2016 at 18:45 John SeenJohn Seen 7315 gold badges17 silver badges34 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 16

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);

发布评论

评论列表(0)

  1. 暂无评论