0

I am new to NodeJS - I am doing this in a AWS lambda function and have the below JSON object

{
  "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.

5
  • What have you tried, and what exactly is the problem with it? Commented May 25, 2020 at 6:35
  • I have tried this - var objectKeysArray = Object.keys(subnetsToUse) objectKeysArray.forEach(function(subnetId) { var objValue = subnetsToUse[subnetId] }) and it returns empty Commented May 25, 2020 at 6:40
  • Edit the question to give a minimal reproducible example. But why wouldn't it? forEach doesn't return anything. Commented May 25, 2020 at 6:42
  • @jonrsharpe I am sorry I did not get what is wrong with my code. Can you explain, please? Commented May 25, 2020 at 6:52
  • 1
    Why did you not put your code in the question? Read minimal reproducible example again: input, code, output. Commented May 25, 2020 at 6:53

1 Answer 1

1

You can use the Array.map or Array.reduce to iterate over the object values and push them into an array for example.

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.