简体   繁体   English

将Nodejs JSON object 转换为列表<string></string>

[英]Convert Nodejs JSON object to List<String>

I am new to NodeJS - I am doing this in a AWS lambda function and have the below JSON object我是 NodeJS 的新手-我在 AWS lambda function 中执行此操作,并具有以下 JSON2668CFDE63931ACCB49

{
  "subnetsToUse": [
    {
      "subnetId": "subnet-0g6e5ad78f2841dc9"        },
    {
      "subnetId": "subnet-089e0d4de075664b3"        },
    {
      "subnetId": "subnet-06778539a55adc513"        }
  ]
}

I need to return a list of subnetIds from this.我需要从这里返回一个子网标识符列表。

subnet-0g6e5ad78f2841dc9,subnet-0g6e5ad78f2841dc9,subnet-0g6e5ad78f2841dc9

Here is what I have tried so far这是我到目前为止尝试过的

var objectKeysArray = Object.keys(subnetsToUse) 
objectKeysArray.forEach(function(subnetId) 
{ var objValue = subnetsToUse[subnetId] })

How do I achieve this in NodeJS.我如何在 NodeJS 中实现这一点。

You can use the Array.map or Array.reduce to iterate over the object values and push them into an array for example.例如,您可以使用Array.mapArray.reduce迭代 object 值并将它们推送到数组中。

 const data = { "subnetsToUse": [ { "subnetId": "subnet-0g6e5ad78f2841dc9", "availabilityZone": "us-west-2c" }, { "subnetId": "subnet-089e0d4de075664b3", "availabilityZone": "us-west-2b" }, { "subnetId": "subnet-06778539a55adc513", "availabilityZone": "us-west-2a" } ] } const mapRes = data.subnetsToUse.map((currentValue) => { return currentValue.subnetId; }); console.log("mapRes", mapRes) const reduceRes = data.subnetsToUse.reduce((accumulator, currentValue) => { accumulator.push(currentValue.subnetId); return accumulator; }, []); console.log("reduceRes",reduceRes)

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

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