简体   繁体   English

如何获取特定键值的数组?

[英]How can I get an array of certain key-values?

var obj = [
  {
    "amount": " 12185",
    "job": "GAPA",
    "month": "JANUARY",
    "year": "2010"
  },
  {
    "amount": "147421",
    "job": "GAPA",
    "month": "MAY",
    "year": "2010"
  },
  {
    "amount": "2347",
    "job": "GAPA",
    "month": "AUGUST",
    "year": "2010"
  }
]

How can i get all amounts, that is '12185' , '147421' , '2347' .我如何获得所有金额,即'12185''147421''2347' I've tried to do this我试过这样做

Object.keys(obj).map(key => obj[key])

Your obj variable is actually an array.您的obj变量实际上是一个数组。 (denoted by the braces [] ) (由大括号[]表示)

You can use the map function on an array to return what you're asking for.您可以在数组上使用 map 函数来返回您所要求的内容。

var amounts = obj.map(x => x.amount); // Array(3) [ " 12185", "147421", "2347" ]

You may also want to append .trim() to the end of x.amount to remove any spaces specifically.您可能还想将 .trim() 附加到 x.amount 的末尾以专门删除任何空格。

var amounts = obj.map(x => x.amount.trim()); // Array(3) [ "12185", "147421", "2347" ]
var obj = [
  {
    "amount": " 12185",
    "job": "GAPA",
    "month": "JANUARY",
    "year": "2010"
  },
  {
    "amount": "147421",
    "job": "GAPA",
    "month": "MAY",
    "year": "2010"
  },
  {
    "amount": "2347",
    "job": "GAPA",
    "month": "AUGUST",
    "year": "2010"
  }
];


var amounts = obj.map(x => x.amount);

console.log(keys); // Array(3) [ " 12185", "147421", "2347" ]

你的obj是一个数组,你需要:

const vals = obj.map(entry => entry.amount); // ["12185", "147421", "2347"]

I believe you're looking for this我相信你正在寻找这个

 var obj = [ { "amount": " 12185", "job": "GAPA", "month": "JANUARY", "year": "2010" }, { "amount": "147421", "job": "GAPA", "month": "MAY", "year": "2010" }, { "amount": "2347", "job": "GAPA", "month": "AUGUST", "year": "2010" } ]; let amounts = obj.map(v => v.amount); console.log(amounts);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM